Reputation: 3565
I'm using array_push
method to get all the integers into array as follows.
$response = json_decode($jsonResponse);
foreach($response as $item) { //foreach element in $response
$type = $item;
$unique_id = $type->id;
$id_array=array();
array_push($id_array, $unique_id);
}
var_dump($id_array);
But the $id_array
contains only last integer element. Is there any wrong with above code or can't we push integer elements into php array?
Upvotes: 0
Views: 2723
Reputation: 10548
Put $id_array=array();
at the beginning of foreach
$response = json_decode($jsonResponse);
$id_array=array();
foreach($response as $item) { //foreach element in $response
$type = $item;
$unique_id = $type->id;
array_push($id_array, $unique_id);
}
var_dump($id_array);
You can Minimize Code inside foreach
$response = json_decode($jsonResponse);
$id_array=array();
foreach($response as $item) { //foreach element in $response
$unique_id = $item->id;
array_push($id_array, $unique_id);
}
var_dump($id_array);
OR
$response = json_decode($jsonResponse);
$id_array=array();
foreach($response as $item) { //foreach element in $response
array_push($id_array, $item->id);
}
var_dump($id_array);
Upvotes: 3
Reputation: 162
$response = json_decode($jsonResponse);
$id_array=array();
foreach($response as $item) { //foreach element in $response
$type = $item;
$unique_id = $type->id;
array_push($id_array, $unique_id);
}
var_dump($id_array);
This should work..
Upvotes: 1
Reputation: 1654
Initialize the array outside the loop :
$response = json_decode($jsonResponse);
$id_array = array();
foreach($response as $item) { //foreach element in $response
$type = $item;
$unique_id = $type->id;
array_push($id_array, $unique_id);
}
Upvotes: 1