Find value of key where value of another key equals matched value (associative array)

拥有回忆 提交于 2019-12-11 02:00:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!