Reputation: 10720
How can I save an array, for example,
['name' => 'Some_name_1', 'Quantity' => 176],
['name' => 'some_name_2', 'Quantity' => 1096],
['name' => 'some_name_3', 'Quantity' => 1598],
from a foreach loop?
For example, I get those values from another array by applying the array_count_values()
function in this form:
Array
(
[Some_name_1] => 176
[Some_name_2] => 1096
[Some_name_3] => 1598
)
And when I apply the foreach()
like this
foreach($values as $index => $value){
$stats=['name'=>$index,'Quantity'=>$value];
}
I only get one value stored in the new array and not the three ones.
Array
(
[name] => Some_name_3
[Quantity] => 1598
)
(Some_name_1, and Some_name_2 weren't stored in the array)
How can I save all of them inside the array? What am I missing?
Upvotes: 0
Views: 86
Reputation: 21
Inside of your foreach loop you're not appending to an array - rather overwriting each time you iterate over the values array.
Append to an array rather than overwriting using the example below.
New function:
foreach($values as $index => $value){
$stats[]=['name'=>$index,'Quantity'=>$value];
}
Upvotes: 1
Reputation: 6785
push to the array, your syntax is incorrect.
foreach(values as $index=>$value)
{
array_push($stats, array('name'=>$index, 'quantity'=>$value));
}
or as Matt says above, alternate syntax:
foreach(values as $index=>$value)
{
$stats[] = array('name'=>$index, 'quantity'=>$value);
}
Upvotes: 1