问题
For example, I have an array of:
array(
array(
['make']=>ford
['color']=>blue
['type']=>automatic
),
array(
['make']=>chevrolet
['color']=>red
['type']=>manual
)
Is is possible to find in PHP the value of a known key when all I have to go on is the value of another key?
Say for example, I have the value "blue" and I know that it's in the "color" key, can I now find what the value of "car" is from this information?
The known value of the known key is unique. (in this example, there couldn't be two values of "blue")
I hope this makes sense, and thanks in advance for your help.
回答1:
$knownColor = 'blue';
$knownKey = 'color';
$desiredKey = 'make';
foreach ($outerArray as $inner) {
if ($inner[$knownKey] == $knownColor) {
$result = $inner[$desiredKey];
// or to get the whole inner array:
// $result = $inner;
break;
}
}
var_dump($result);
回答2:
Assuming your array is assigned to $cars it would go something like this:
$knownColor = 'blue';
$knownKey = 'color';
...
foreach ($cars as $car) {
if ($car[$knownKey] === $knownColor) {
return $car;
}
}
来源:https://stackoverflow.com/questions/8836465/find-value-of-key-where-value-of-another-key-equals-matched-value-associative-a