Is it possible to traverse a JSON with for cycle? (do not use foreach)

2

I have a JSON that is easy to navigate with a foreach, the structure of the JSON is the following:

{
 "llave":"valor","llave":"valor","llave":"valor"
}

foreach ($arrayJson as $key => $value) {
    echo $key . ': ' . $val;
}

I would like to know if there is a way to extract the keys and values with a for cycle in PHP.

    
asked by Igmer Rodriguez 21.09.2018 в 21:03
source

2 answers

4

I do not know if there is any justified reason to avoid using foreach .

If you want other alternatives, apart from what @juan indicates, there are other alternatives, but I want to be clear that none is better than foreach :

In alternatives 1 to 3 we will create the array as of JSON:

$strJson='
{
 "llave1":"valor1","llave2":"valor2","llave3":"valor3"
}';

$arrayJson=json_decode($strJson);

1. Using array_walk :

array_walk($arrayJson, function(&$v, $k) { $v = "$k: $v".PHP_EOL; echo $v;});

2. With while and also using list and each

That is, two additional functions .

while (list($k, $v) = each($arrayJson)) {
    echo "$k: $v".PHP_EOL;
}

3. Using foreach what you do not want precisely, but the best

This is the simplest and fastest:

foreach ($arrayJson as $k => $v) {
    echo $k . ': ' . $v.PHP_EOL;
}

There must be a very justified reason for not wanting to use it:)

4. Using array_map

In this case, we are going to build the array from the JSON like this:

$arrayJson=json_decode($strJson,TRUE);

And we use array_map combined with array_keys . In the callback we print the keys and the values:

$callback = function ($k, $v) {
    echo "$k: $v".PHP_EOL;
    //return array($k => $k);
  };

array_map( $callback, array_keys($arrayJson), $arrayJson);

In all three codes the output is the same:

Exit:

llave1: valor1
llave2: valor2
llave3: valor3
    
answered by 21.09.2018 / 21:32
source
0

You can use the function each

for($i=0;$i<count($arrayJson);$i++)
    {
        list($key, $val)=each($arrayJson);
        echo $key . ': ' . $val;
    }
    
answered by 21.09.2018 в 21:23