-1

i have a JSON that i decode into array:

$json = '[{"CODICE":"A","COD. CRISI":1},{"CODICE":"25","COD. CRISI":1}]';

$arraydati = json_decode($json);

If i do print_r($arraydati);, i have this array:

Array
(
    [0] => stdClass Object
        (
            [CODICE] => A
            [COD. CRISI] => 1
        )

    [1] => stdClass Object
        (
            [CODICE] => 25
            [COD. CRISI] => 1
        )


)

Now i want iterate the array and if "Codice" contains 25 i read the value.

I have a foreach loop

foreach($arraydati as $key=>$value){
    if($key['CODICE'] === '1'){
            echo($value['COD. CRISI']);
        }
    }

but non print nothing, where is the problem?

Federico
  • 11
  • 4
  • 1
    Hint: you've decoded the JSON as objects with properties, but you try to access them like arrays. I'm surprised you don't have any warnings or errors? – ADyson Mar 21 '23 at 10:43
  • 1
    Did you check what `$key` contains? Usually, that is an **array key**, and array keys itself cannot be arrays – Nico Haase Mar 21 '23 at 10:49

1 Answers1

1

Your first loop result in an object, so you'll need ->.

Also, foreach gives you the $key and $value, but if you use $key you'll still need to target that key in $arraydati: $arraydati[$key].

Much easier to use the $value!

<?php

$json = '[{"CODICE":"A","COD. CRISI":1},{"CODICE":"25","COD. CRISI":1}]';

$arraydati = json_decode($json);

foreach ($arraydati as $value) {
    if ($value->CODICE === '25') {
        echo($value->{'COD. CRISI'});
    }
}
1
0stone0
  • 34,288
  • 4
  • 39
  • 64