简体   繁体   中英

php json decode result in another json decode

I have 2 json data from nosql . first match if the search word match in $array1 , get the item number then put item number into $array2 , get the price of custom search require. But my code cause Invalid argument supplied for foreach() in foreach($json2[$num] as $data2)

$str = 'paper';
$array1 = '[{"a":"1","b":"book"},{"a":"2","b":"paper"}]';  
$array2 = '[{"1":["17.00","22.00"]},{"2",["4.50","6.00"]}]';
$json1 = json_decode($array1);
$json2 = json_decode($array2,true);
foreach($json1 as $data1){
    if(preg_match('#'.$data1->b.'#',$str,$match)){
        $num = $data1->a; // $num = 2
    }
}
foreach($json2[$num] as $data2){
    foreach($data2 as $newdata){
        echo $newdata.'<br />'; // 4.50, 6.00
    }
}

If $num = 2 in your comments is correct, you'll be accessing the third element in $json2 but you can't since there only are two.

Update
Oops, how did I miss this? Your $array2 already has the indices right there, you're just not loading them properly. You can simply loop through $array2 and look for the key. However, a better solution would be to load the data properly, by filling $array2 as a dictionary rather than a list.

First off your JSON for $array2 is not valid. It should be:

[{"1":["17.00","22.00"]},{"2":["4.50","6.00"]}]
-----------------------------^
This should be a ":", not a ","

Your JSON is actually an array of objects (arrays). var_dump($json2); shows this.

array(2) {
  [0]=>
  array(1) {
    [1]=>
    array(2) {
      [0]=>
      string(5) "17.00"
      [1]=>
      string(5) "22.00"
    }
  }
  [1]=>
  array(1) {
    [2]=>
    array(2) {
      [0]=>
      string(4) "4.50"
      [1]=>
      string(4) "6.00"
    }
  }
}

You're gonna need to loop over it like this:

foreach($json2 as $data2){
    if(array_key_exists($num, $data2)){
      $data2 = $data2[$num];
      foreach($data2 as $newdata){
          echo $newdata.'<br />'; // 4.50, 6.00
      }
    }
}

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