使用php [duplicate]搜索关联数组数组中的值

时间:2023-01-13 12:47:53

This question is an exact duplicate of:

这个问题与以下内容完全相同:

How to find the array which contains moo == 'gyu'?

如何找到包含moo =='gyu'的数组?

$arr = [
  ['moo' => 'abc', 'foo' => 1], ['moo' => 'gyu', 'foo' => 2] ...
]

I know that should be answered already but unfortunately I wasn't able to find an example.

我知道应该已经回答,但不幸的是我无法找到一个例子。

Thank you.

2 个解决方案

#1


2  

Use array_filter() to to find target array. In callback function check value of moo index.

使用array_filter()来查找目标数组。在回调函数中检查moo索引的值。

$newArr = array_filter($arr, function($item){
    return $item['moo'] == 'gyu';
});

Also you can use array_reduce() that return target array in result.

您也可以使用在结果中返回目标数组的array_reduce()。

$newArr = array_reduce($arr, function($carry, $item){
    $item['moo'] == 'gyu' ? $carry = $item : "";
    return $carry;
 });

Check result in demo

在演示中检查结果

#2


1  

You have to used array_search() function for that.

你必须使用array_search()函数。

if(array_search('gyu', array_column($arr, 'moo')) !== False) {
    echo "FOUND";
} else {
    echo "Not Found";
 }

#1


2  

Use array_filter() to to find target array. In callback function check value of moo index.

使用array_filter()来查找目标数组。在回调函数中检查moo索引的值。

$newArr = array_filter($arr, function($item){
    return $item['moo'] == 'gyu';
});

Also you can use array_reduce() that return target array in result.

您也可以使用在结果中返回目标数组的array_reduce()。

$newArr = array_reduce($arr, function($carry, $item){
    $item['moo'] == 'gyu' ? $carry = $item : "";
    return $carry;
 });

Check result in demo

在演示中检查结果

#2


1  

You have to used array_search() function for that.

你必须使用array_search()函数。

if(array_search('gyu', array_column($arr, 'moo')) !== False) {
    echo "FOUND";
} else {
    echo "Not Found";
 }