1

I have an array, what Is like this:

 $itemx=
 [
     'Weapons'=>[
          'Sword'=> [
              'ID'   => '1',
             'Name'   => 'Lurker',
             'Value'  => '12',
             'Made'   => 'Acient'
           ],

           'Shield'=> [
              'ID'   => '2',
              'Name'   => 'Obi',
              'Value'  => '22',
              'Made'   => 'Acient'
            ],

            'Warhammer'=> [
                'ID'   => '3',
               'Name'   => 'Clotch',
               'Value'  => '124',
               'Made'   => 'Acient'
             ]
     ],
     'Drinks'=>[
       'Water'=> [
          'ID'   => '4',
          'Name'   => 'Clean-water',
          'Value'  => '1',
          'Made'   => 'Acient'
        ],

        'Wine'=> [
            'ID'   => '5',
           'Name'   => 'Soff',
           'Value'  => '5',
           'Made'   => 'Acient'
         ],

         'Vodka'=> [
            'ID'   => '6',
            'Name'   => 'Laudur',
            'Value'  => '7',
            'Made'   => 'Acient'
          ]
     ]


 ];

I want to find an array from it by Name or ID, so my output should be like this.

*Search by ID=4*

 'Water'=> [
          'ID'   => '4',
          'Name'   => 'Clean-water',
          'Value'  => '1',
          'Made'   => 'Acient'
        ]

I look at other topics and found that I should use array_search

But It didn't work. I tried like this:

$arra=$itemx["Drinks"];

$key = array_search(4, array_column($arra, 'ID'));
  var_dump($arra[$key]);

It also dident work when I tried with Name as a search key.

How can I get this working?

Godhaze
  • 155
  • 3
  • 16
  • Possible duplicate of [PHP multidimensional array search by value](https://stackoverflow.com/questions/6661530/php-multidimensional-array-search-by-value) – Muhammad Ibnuh Aug 29 '17 at 21:27

2 Answers2

2

You can do it like below:-

$search_id = 4;
$final_array = [];
 foreach($itemx as $key=>$val){
  foreach($val as $k=>$v){
    if($v['ID'] == $search_id){
      $final_array[$k] =  $itemx[$key][$k];
    }
  }
 }
 print_r($final_array);

https://eval.in/852123

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
2

This should probably get you what you want.

function rec($itemx,$search=4){
    foreach ($itemx as $key => $value) {
        if (is_array($value)) {
            foreach ($value as $k => $v) {
                if ($v['ID'] == $search) {
                    return $value;  
                }
            }
        }
    }
}
print_r(rec($itemx,4));
Kyle Brown
  • 21
  • 4