I have the following array which I want to make readable for users:
Array
(
[3] => Array
(
[id] => 3
[price] => 4.00
[per] => day
[count] =>
[type] => single
[status] => T
[extra_quantity] => 1
)
[2] => Array
(
[id] => 2
[price] => 12.00
[per] => day
[count] =>
[type] => single
[status] => T
[extra_quantity] => 1
)
)
I want to echo this to show users the following readable line for every subarray:
[id] = [price] per [day]
I am fairly new to arrays, especially nested one like the one I have above, how should I go with this to get an output like I need? Thanks!
FOreach loops are used when iterating over arrays.The above is a multi-dimensional array. Meaning An array in an array
foreach($array as $value):
if(array_key_exists($value['id'], $value) && array_key_exists($value['price'], $value) && array_key_exists($value['per'], $value)):
#we have the keys present.
echo $value['price'].'per'.$value['per'];
endif;
endforeach;
use foreach()
built in function which help you get all data as readable
foreach ($rows as $row) {
echo $row['price'].'per'.$row['per'];
echo "<br>";
}
check for more information
Must more optimized than two foreach loops,
list($id,$price, $day) = [array_column($your_arr, 'id'),array_column($your_arr, 'price'),array_column($your_arr, 'day')];
foreach($id as $k => $v)
{
echo $v ." = ".$price[$k]." per ". $day[$k];
}
array_column
Return the values from a single column in the input array.
I hope this will help.