2

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"
MH2K9
12.1k7 gold badges34 silver badges49 bronze badges
asked Jul 31, 2019 at 7:37
3
  • what problem have you faced? show your code Commented Jul 31, 2019 at 7:45
  • And what did you try to achieve this? As it stands right now, there is no question, just requirements. Commented Jul 31, 2019 at 7:45
  • i dont know how i can foreach random num, as like that: foreach($res["result"]["result"]["get_????"] as $value) Commented Jul 31, 2019 at 7:51

1 Answer 1

1

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

answered Jul 31, 2019 at 7:51
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.