0

I have this array, i am trying to get the "id" when sku matches to 'Testproduct_2327'.

I am not sure how to implement this.

$main_array = array (
  'status' => true,
  'response' => 
    array (
      'code' => 200,
      'result' => 
      array (
        'products' => 
        array (
          0 => 
          array (
            'id' => '0242e39e-bf20-11eb-fc6f-4cc6b4b8af34',
            'sku' => 'Testproduct_0'
            ),
          1 => 
          array (
            'id' => '0242e39e-bf20-11eb-fc6f-4cc6b6682978',
            'handle' => 'vend_2327handle',
            'sku' => 'Testproduct_1'
          ),
          2 => 
          array (
            'id' => '0242e39e-bf20-11eb-fc6f-4cc6d31d1d02',
            'handle' => 'vend_2327handle',
            'sku' => 'Testproduct_2327',
        ),
      ),
    ),
  )
);

I have tried this & it not working

     array_walk_recursive($main_array, function ($item, $key) {
      if($key == "sku" && $item == "Testproduct_2327"){
      echo $item;
      }
});

Any thoughts on this ? php compiler - https://rextester.com/AKIXIC51695

Thanks

  • Simply looping over `$main_array['response']['result']['products']` (and stopping when you found the right one) should be more straightforward and efficient. – Jeto Jan 02 '21 at 08:05
  • You were trying to get ID. Did you get it? This is the most efficient way if number of levels are dynamic. – nice_dev Jan 02 '21 at 08:05
  • See also [PHP multidimensional array search by value](https://stackoverflow.com/q/6661530/90527) and [Find Key value in nested Multidimensional Array](https://stackoverflow.com/q/50806604/90527). – outis Jan 02 '21 at 13:15

1 Answers1

0

You are almost there. You just have to pass an ID variable to the callback using pass by reference to manipulate the same ID in its scope as well, like below:

<?php

$id = '';
array_walk_recursive($main_array, function ($item, $key) use (&$id){
    //echo "$key holds $item\n";
      if($key === 'id'){
          $id = $item;
      }else if($key == "sku" && $item == "Testproduct_2327"){
          echo $id;
      }
});

For dynamic variable, you can do like below:

<?php

$id = '';
$compare_sku = 'Testproduct_2327';
array_walk_recursive($main_array, function ($item, $key) use (&$id,&$compare_sku){
    //echo "$key holds $item\n";
      if($key === 'id'){
          $id = $item;
      }else if($key == "sku" && $item == $compare_sku){
          echo $id,"<br/>";
      }
});
nice_dev
  • 17,053
  • 2
  • 21
  • 35