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

3
  • Simply looping over $main_array['response']['result']['products'] (and stopping when you found the right one) should be more straightforward and efficient. Commented Jan 2, 2021 at 8:05
  • You were trying to get ID. Did you get it? This is the most efficient way if number of levels are dynamic. Commented Jan 2, 2021 at 8:05
  • See also PHP multidimensional array search by value and Find Key value in nested Multidimensional Array. Commented Jan 2, 2021 at 13:15

1 Answer 1

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/>";
      }
});
Sign up to request clarification or add additional context in comments.

7 Comments

I am not sure what's wrong with in my system in it , its not working. i just pass dynamic variable for "Testproduct_2327". i have checked its data type & value its same, still not working.
@devphp Can you share your code using some link?
@devphp perhaps, are you trying to collect all IDs who match?
Sure, let me update
Actually i when write static "Testproduct_2327" it works but not with dynamic variable.
|