简体   繁体   中英

Get value from key in an array in PHP

I have the following array in PHP:

Array
(
    [0] => Array
        (
            [name] => category
            [value] => OUT
        )
    [1] => Array
        (
            [name] => Name_Fr
            [value] => p
        )
...

How can I get the value if I know the name ?

I tried:

$value = $array['name']['Name_Fr'];

Thanks.

您将必须遍历所有索引,以找到名称匹配的地方。

If you're running PHP 5.5, you can do a lot with array_column() , such as:

$newArray = array_column($oldArray, 'value', 'name');
$value = $newArray[$knownName];

or even (using array dereferencing):

$value = array_column($oldArray, 'value', 'name')[$knownName];

For earlier versions of PHP, you could do something like:

$value = array_filter(
    $oldArray, 
    function ($value) use ($knownName) { 
        return $value['name'] == $knownName; 
    }
);
$value = array_shift($value);
echo $value['value'], PHP_EOL;

since it's an array of arrays, a loop would help you do so.

foreach($arrays as $array)
{
  $value = $array[value]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM