echo array inside array in order - php

I have this some arrays that look like this,
$array = Array(
'Homer' => Array
(
'id' => 222,
'size' => 12
),
'Bart' => Array
(
'id' => 333,
'size' => 3
)
);
I would like to echo Homer: id is 222, size is 12
then in the next line echo Bart: id is 333, size is 3 using a foreach loop as key and values.
So i basically want to echo all the Simpsons character names which have their id and size next their names.
I tired this but it printed homer too many times and it even used Bart's id and size at one point.
foreach( $array as $billdate => $date) {
foreach( $date as $k => $v) {
echo $billdate; // Prints Homer and bart
foreach($array as $innerArray){
foreach($innerArray as $key => $value){
echo "[". $key ."][". $value ."] <br/>";
}}
}
}
Thanks in advance.

you can try like this:
foreach( $array as $billdate => $date) {
echo $billdate.': id is '.$date['id'].', size is '.$date['size'];
}

Don't use so many foreach ,just think your need loop ...
foreach( $array as $billdate => $date) {
echo $billdate; // Prints Homer and bart
foreach($date as $key => $value){
echo "[". $key ."][". $value ."] <br/>";
}
}

Related

According to what I know you cannot echo an array. You have to loop through it. Why are the values of my array printed?

I have this data:
1CPT5
'stock' => array (
'warehouse' =>
array (
'warehouse_id' => 1,
'name' => 'CPT',
),
'quantity_available' => 5,
)
3JHB21
'stock' = > array (
'warehouse' =>
array (
'warehouse_id' => 3,
'name' => 'JHB',
),
'quantity_available' => 21,
)
and this code that is looping through the above data.
foreach ($row['stock'] as $val) {
foreach ($val['warehouse'] as $warehouse => $name) {
echo $name;
}
echo $val['quantity_available'];
echo '<pre>' . var_export($val, true) . '</pre>';
}
I am trying to display the quantity_available based on the ID of the warehouse (there are 2 warehouses) The first set of data is for warehouse_id 1 with name CPT and number of items 5.
The second set of data is for warehouse_id 3 with name JHB and number of items 21.
'warehouse' is an array and according to what I know you can only loop through an array, print_r or var_dump an array. Why if I then echo $name do I see all the values of the array and how do I isolate them so I can just get the id and based on the id display the quantity associated with that id?
I finally figured it out and the following code displays the number I am after:
foreach ($row['stock_at_takealot'] as $key => $val) {
foreach ($val['warehouse'] as $key => $value) {
if ($value == 1) {
echo $val['quantity_available'];
}
}
};
but now I have another issue where all the values are displayed in one cell instead of two. What is my mistake here please?
<td class='small centerCol'>";
foreach ($row['stock_at_takealot'] as $key => $val) {
foreach ($val['warehouse'] as $key => $value) {
if ($value == 1) {
echo $val['quantity_available'];
}
}
};
"</td>
<td class='small centerCol'>";
foreach ($row['stock_at_takealot'] as $key => $val) {
foreach ($val['warehouse'] as $key => $value) {
if ($value == 3) {
echo $val['quantity_available'];
}
}
};
"</td>
<td class='small centerCol'>"

get key value for each single array element

$arr = ['night' => 'black', 'sun' => 'light', 'she' => 'gold'];
foreach ($arr as $el) {
echo ... . '<br>';
}
result should be:
night
sun
she
Thanks
You can print key name like this:
$arr = ['night' => 'black', 'sun' => 'light', 'she' => 'gold'];
foreach ($arr as $key => $el) {
echo $key. ' <br>';
}
Output:
night
sun
she
You should use:
<?php $array_keys = array_keys($your_array);
try this
$key contain all your array key and $value contain all your value
$arr = ['night' => 'black', 'sun' => 'light', 'she' => 'gold'];
foreach ($arr as $key=>$value) {
echo $key."=".$value."<br>";
}

Change value in multidimension associative array PHP

I must be missing something about how PHP arrays are handled. When I execute the following code:
<?php
$ary = array(
"alpha" => array("A"=>1,"B"=>2,"C"=>3),
"beta" => array("A"=>7,"B"=>8,"C"=>9)
);
foreach ($ary as $key => $vals) {
$vals["B"]=99;
echo $key."= ".$vals["A"]." ".$vals["B"]." ".$vals["C"]."<br>";
}
echo $ary['alpha']["B"]."<br>";
?>
I get:
alpha= 1 99 3
beta= 7 99 9
2
The change to 99 in each case seems to be lost. What am I doing wrong?
If you want to change items of array in foreach statement you should pass by reference.
foreach ($ary as $key => &$vals) {
}
<?php
$ary = array(
"alpha" => array("A"=>1,"B"=>2,"C"=>3),
"beta" => array("A"=>7,"B"=>8,"C"=>9)
);
foreach ($ary as $key => $vals) {
//$vals["B"]= 99;
$ary[$key]["B"] = 99;
echo $key."= ".$vals["A"]." ".$vals["B"]." ".$vals["C"]."<br>";
}
echo $ary['alpha']["B"]."<br>";
?>

Array ksort only shows non-like values?

Have an array for a ranking script.
Some times the key will be the same. They are numeric.
When the sort is ran, only non-like values are echoed.
Can't figure out the fix.
$list = array( $value1 => 'text', $value2 => 'text', $value3 => 'text');
krsort($list);
foreach ($list as $key => $frame) {
echo $frame;
}
If you assign two values to the same key in an array, the first value will be overridden by the second. You'll therefore end up with only one value for that key in the array.
To resolve this, I'd suggest to change your array structure like this:
<?php
$list = array( $key1 => array($key1member1, $key2member2),
$key2 => array($key2member1),
$key3 => array($key3member1, $key3member2, $key3member3) );
krsort($list);
foreach ($list as $key => $frames) {
foreach ($frames => $frame) {
echo $frame;
}
}
?>
Going by what you wrote in the comments to this question and my other answer, I'd recommend to switch keys and values.
<?php
$list = array( "frame1" => 4, "frame2" => 2, "frame3" => 99, "frame4" => 42 );
arsort($list);
foreach ($list as $frame => $ranking) {
echo $frame;
}
?>

Sum for values in my array

I have an array like below, and I want to do the total of values in a spefic manner where all values of val1_(.*) {regular expressions}, and similarly other values.
I have only specific vals like val1, val2, and val3.
My array is like:
$stats = Array
(
[ADDED_NEW_2012_06_12] => 16
[ADDED_OLD_2012_06_12] => 10
[ADD_LATER_2012_06_12] => 12
[ADDED_NEW_2012_06_11] => 16
[ADDED_OLD_2012_06_11] => 10
[ADD_LATER_2012_06_11] => 12
)
Can you please tell me how can i obtain my result. I don't know how to add such values using regex in php. Please help.
You don't necessarily need a regular expression if you can identify the values by the first part of the key.
Iterate over the array and create a new array with one element for each valX:
$totals = array();
// iterate over the array
foreach($array as $key => $value) {
$k = substr($key, 0, strpos($key, '_')); // get the first part (i.e. `valX`)
if(!isset($totals[$k])) { // if $totals['valX'] does not exist, initialize
$totals[$k] = 0;
}
$totals[$k] += $value; // sum
}
Reference: foreach, substr, strpos, isset
Do you mean this?
$array = array (
'val1_2012_06_12' => 16,
'val2_2012_06_12' => 10,
'val3_2012_06_12' => 12,
'val1_2012_06_11' => 16,
'val2_2012_06_11' => 10,
'val3_2012_06_11' => 12,
);
$sums = array();
foreach ($array as $key => $value) {
$regex = '~(?P<prefix>val\d+)_\d{4}_\d{2}_\d{2}~';
if (preg_match($regex, $key, $matches)) {
$sums[$matches['prefix']] += $value;
}
}
It will produce something like this, it will group sums by prefixes:
Array
(
[val1] => 32
[val2] => 20
[val3] => 24
)
Edit: updated to the refined question
You can match the key against a code, and create a sum from there like this with a simple foreach loop.
$array = array(
'ADDED_NEW_2012_06_12' => 16,
'ADDED_OLD_2012_06_12' => 10,
'ADD_LATER_2012_06_12' => 12,
'ADDED_NEW_2012_06_11' => 16,
'ADDED_OLD_2012_06_11' => 10,
'ADD_LATER_2012_06_11' => 12,
);
$sumarray = array();
foreach ($array as $key => $value)
{
$matches = array();
preg_match("/^(\w+?_\w+?)_/i", $key, $matches);
$key = $matches[1];
if (!isset($sumarray[$key]))
{
$sumarray[$key] = $value;
} else {
$sumarray[$key] = $sumarray[$key] + $value;
}
}
print_r($sumarray);
if you have just this tree type of value in array so you can use this:
$stats = Array(
'ADDED_NEW_2012_06_12' => 16,
'ADDED_OLD_2012_06_12' => 10,
'ADD_LATER_2012_06_12' => 12,
'ADDED_NEW_2012_06_11' => 16,
'ADDED_OLD_2012_06_11' => 10,
'ADD_LATER_2012_06_11' => 12
);
foreach($stats as $key => $value)
{
$substring=substr($key, 0 , 9);
if($substring=='ADDED_NEW')
#$ADDED_NEW += $value;
elseif($substring=='ADDED_OLD')
#$ADDED_OLD += $value;
else
#$ADD_LATER += $value;
}
echo 'ADDED_NEW : ' . $ADDED_NEW .'<br>ADDED_OLD : ' . $ADDED_OLD .'<br>ADD_LATER : ' . $ADD_LATER ;
Output :
ADDED_NEW : 32
ADDED_OLD : 20
ADD_LATER : 24
$sum = 0;
Foreach($object as $key=>$value){
$sum += $value;
}

Categories