Parsing JSON Array with PHP Foreach

Parsing JSON array with PHP foreach

You maybe wanted to do the following:

foreach($user->data as $mydata)

{
echo $mydata->name . "\n";
foreach($mydata->values as $values)
{
echo $values->value . "\n";
}
}

Parse JSON with PHP using foreach

You can try this:

$data=json_decode($data,true);//converts in array

foreach($data['league'] as $key=>$val){// this can be ommited if only 0 index is there after
//league and $data['league'][0]['events'] can be used in below foreach instead of $val['events'].
foreach($val['events'] as $keys=>$value){
echo $value['home'].' v '.$value['away'].'<br>;
}
}

Parsing JSON object foreach

Your JSON is not an array, it's an object. The data property in this object is the array you want.

$obj = json_decode($content, true);

foreach ($obj['data'] as $value) {
echo $value['txID'];
}

PHP - Decode JSON array and use in foreach loop

In your loops, $stats is referring to the value of each element in the array. I think you're looking for $array['playerCredentials']['playerId'];. If you want to iterate over all properties of a player, you could do this:

foreach ($array['playerCredentials'] as $key => $value) {
printf('%s => %s<br />', $key, $value);
}

How can i parse this json file in php?

You can use simple foreach loop like this.

Code

<?php

$json = '{"Files":[{"name":"Tester","Dir":true,"path":"/stor/ok"},{"name":"self","Dir":true,"path":"/stor/nok"}]}';
$json = json_decode($json, true);

?>
<!DOCTYPE html>
<html>
<body>
<table border="1">
<tr><td>name</td><td>Dir</td><td>path</td></tr>
<?php foreach ($json["Files"] as $k => $v): ?>
<tr>
<td><?php echo htmlspecialchars($v["name"]); ?></td>
<td><?php echo htmlspecialchars($v["Dir"]); ?></td>
<td><?php echo htmlspecialchars($v["path"]); ?></td>
</tr>
<?php endforeach; ?>
</table>
</body>
</html>

Result

screenshot result

php: loop through json array

Set the second function parameter to true if you require an associative array

Some versions of php require a 2nd paramter of true if you require an associative array

$json  = '[{"var1":"9","var2":"16","var3":"16"},{"var1":"8","var2":"15","var3":"15"}]';
$array = json_decode( $json, true );


Related Topics



Leave a reply



Submit