简体   繁体   中英

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. 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. 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($myArray, fn($v) => in_array(100, $v['score']));

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

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);

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