从PHP数组中的键获取值

时间:2023-02-09 21:37:28

I have the following array in PHP:

我有以下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.

谢谢。

3 个解决方案

#1


2  

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

如果您正在运行PHP 5.5,您可以使用array_column()来做很多事情,比如:

$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:

对于PHP的早期版本,您可以执行以下操作:

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

#2


2  

You would have to loop through all indexes finding where the names match.

您必须循环遍历所有索引,查找名称匹配的位置。

#3


1  

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

因为它是数组,所以循环可以帮助您这样做。

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

#1


2  

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

如果您正在运行PHP 5.5,您可以使用array_column()来做很多事情,比如:

$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:

对于PHP的早期版本,您可以执行以下操作:

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

#2


2  

You would have to loop through all indexes finding where the names match.

您必须循环遍历所有索引,查找名称匹配的位置。

#3


1  

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

因为它是数组,所以循环可以帮助您这样做。

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