Semyashkin
Semyashkin

Reputation: 23

Foreach Json Array

I have array, where get_# have random number. Need to foreach all items [result][result][get_#RAND_NUM#] and take [id], [name]. Thanks! Array:

-[result]
--[result]

---[get_1]
----[id] = "1"
----[name] = "dog"

---[get_6]
----[id] = "53"
----[name] = "cat"

Upvotes: 2

Views: 90

Answers (1)

MH2K9
MH2K9

Reputation: 12039

According to PHP manual the foreach makes an iteration over array or object. foreach provides $key and $value options. From this $key var you can get the random number you expect.

The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable.

$data = ['result' => [
    'result' => [
        'get_1' => ['id' => 1, 'name' => 'doc'],
        'get_6' => ['id' => 2, 'name' => 'cat'],
    ]
]];
$new_data = [];
foreach ($data['result']['result'] as $key => $val) {
    // If you want to get the random number uncomment the below line
    // $random_no = explode('_', $key)[1]; echo $random_no;
    echo "For key {$key}, id = {$val['id']} and name = {$val['name']} </br>";
    $new_data[] = ['id' => $val['id'], 'name' => $val['name']];
}

print '<pre>';
print_r($new_data);

Demo

Upvotes: 1

Related Questions