简体   繁体   English

在多维数组中搜索值

[英]search value in multidimensional array

I have an array and search for the value 100 - the result should gives me the key of the array.我有一个数组并搜索值 100 - 结果应该给我数组的键。 this works like this:这像这样工作:

$myArray = array(
        array(
            'score'   => '100',
            'name'    => 'Sam',
            'subject' => 'Data Structures'
        ),
        array(
            'score'   => '200',
            'name'    => 'Tanya',
            'subject' => 'Advanced Algorithms'
        ),
        array(
            'score'   => '300',
            'name'    => 'Jack',
            'subject' => 'Distributed Computing'
        )
    );
      
$id = array_search('100', array_column($myArray, 'score'));

But now the "column" score should be an array, too:但是现在“列”分数也应该是一个数组:

$myArray = array(
        array(
            'score'   => array('100','200'),
            'name'    => 'Sam',
            'subject' => 'Data Structures'
        ),
        array(
            'score'   => array('300','400'),
            'name'    => 'Tanya',
            'subject' => 'Advanced Algorithms'
        ),
        array(
            'score'   => array('500','600'),
            'name'    => 'Jack',
            'subject' => 'Distributed Computing'
        )
    );

But now my array_search part doesn't work.但现在我的 array_search 部分不起作用。 How can I solve this?我该如何解决这个问题?

You can use array_filter and then use in_array on the scores key thus returning arrays that have a value of 100 .您可以使用array_filter然后在scores键上使用in_array ,从而返回值为100的 arrays 。

array_filter($myArray, fn($v) => in_array(100, $v['score']));

Output: Output:

array(1) {
  [0]=>
  array(3) {
    ["score"]=>
    array(2) {
      [0]=>
      string(3) "100"
      [1]=>
      string(3) "200"
    }
    ["name"]=>
    string(3) "Sam"
    ["subject"]=>
    string(15) "Data Structures"
  }
}

See it working over at 3v4l看到它在 3v4l 上工作

This works exactly the same way as your first block这与您的第一个块完全相同

$id = array_search(100, array_merge(array_column(array_column($myArray, 'score'), 0), array_column(array_column($myArray, 'score'), 1)));

OR you can write it this way for readability或者你可以这样写以提高可读性

$tempArray1 = array_column(array_column($myArray, 'score'), 0);
$tempArray2 = array_column(array_column($myArray, 'score'), 1);
$myArray2 = array_merge($tempArray1, $tempArray2);
    

      
$id = array_search('100', $myArray2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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