PHP - While loop - php

print "<ul>";
foreach ($arr as $value) {
echo("<li>" . $value[storeid] . " " . ($value[dvdstock] + $value[vhsstock]) . "</li>");
}
print "</ul>";
Will output
•2 20
•2 10
•1 20
•1 20
•1 10
I was wondering how I would adapt this loop so it outputs the total values for each &value[storeid]
•1 50
•2 30
Thanks very much :)

Use another array to calculate the values you want:
// setup a quick place to store the data
$stores = array();
foreach ($arr as $value) {
if(!isset($stores[$value['storeid']])){ // init check required to avoid Notices
$stores[$value['storeid']] = $value['dvdstock'] + $value['vhsstock'];
}else{
$stores[$value['storeid']] += $value['dvdstock'] + $value['vhsstock'];
}
}
ksort($stores); // sort by storeid ASC
print "<ul>";
// loop through the new data
foreach ($stores as $id => $value) {
echo("<li>" . $id . " " . ($value) . "</li>");
}
print "</ul>";
Demo Link

If you are getting the data from an SQL database then you should do this using SUM() functions in the SQL as it is more efficient. If the data source is from somewhere else you should do something like this:
//Sum data
foreach ($arr as $value) {
if (!isset($sums[$value['storeid']])) { // init check required to avoid Notices
$sums[$value['storeid']] = $value['dvdstock'] + $value['vhsstock'];
} else {
$sums[$value['storeid']] += $value['dvdstock'] + $value['vhsstock'];
}
}
ksort($sums); // sort by storeid ASC
print "<ul>";
foreach ($sums as $key => $sum) {
echo("<li>$key $sum</li>");
}
print "</ul>";
Demo Link

It is a for loop and you have to make two of them. First to compute the sum and then to iterate over these values:
$data = array();
foreach ($arr as $value) {
if (!isset($data[$value['storeid']])) { // init check required to avoid Notices
$data[$value['storeid']] = $value['dvdstock'] + $value['vhsstock'];
} else {
$data[$value['storeid']] += $value['dvdstock'] + $value['vhsstock'];
}
}
ksort($data); // sort by storeid ASC
print "<ul>";
foreach ($data as $storeid => $sum) {
echo('<li>' . $storeid . ' ' . ($sum) . '</li>');
}
print "</ul>";
Demo Link
Btw one word about strings:
Either use single quotes ' with concatenation .: 'foo: ' . $bar.
Or double quotes " and put the variables inside the string: "foo: $bar".

<?php
$sums = array();
foreach ($arr as $value)
{
$sums[$value['storeid']] += $value['dvdstock'];
}
print_r($sums);
?>

Correct version:
<?php
$initial = array (
array (
'id' => 1,
'amount' => 10
),
array (
'id' => 1,
'amount' => 10
),
array (
'id' => 2,
'amount' => 20
),
array (
'id' => 2,
'amount' => 20
),
array (
'id' => 2,
'amount' => 20
),
);
$result = array ();
foreach ($initial as $value) {
$result[$value['id']] += $value['amount'];
}
print_r($result);
?>

Related

how to break foreach loop - array index

My array which is dynamic, formed as
$exam = explode(',',$row['exam']);
For example result is:
$exam = array("First-Term","Second-Term", "Third-Term");
We can get index and value as this
foreach (array_values($exam) as $i => $value) {
echo "$i: $valuen";
echo "//And its mark";
}
But, how can I break loop to each index. I have to fetch as follow
First-Term
//And its mark
Second-Term
// And its mark
Third-Term
// And its mark
But while using foreach loop, I am getting
First-Term
Second-Term
Third-Term
//And its mark
//And its mark
//And its mark
How to break loop to each index, after that we use same code in every index. I'm simply try to assign each marks to each term
$exam[0]{
//here is $value
//rest of the code, same code to every index
}
$exam[1]{
//here is $value
//rest of the code, same code to every index
}
$exam[2]{
//here is $value
//rest of the code, same code to every index
}
$exam[...]{
//
}
You should make two arrays for team and marks and then parse these two arrays in the same foreach loop like this
$team = array('a', 'b', 'c', 'd' );
$marks = array('1', '2', '3', '4' );
foreach(array_combine($team, $marks) as $t => $m) {
echo $t . "<br>" .$m . "<br><br>"; //$t for team and m for marks
echo "<br/>";
}
In this way you can parse your different data in a paralell way
From the looks of what you are doing, you are using two foreach loops with different output...
This one:
$exam = array("First-Term","Second-Term", "Third-Term");
foreach (array_values($exam) as $i => $value) {
echo "{$value}<br>";
echo "// And its mark<br><br>";
}
Will output this:
First-Term
//And its mark
Second-Term
// And its mark
Third-Term
// And its mark
While this loop:
$exam = array("First-Term","Second-Term", "Third-Term");
foreach (array_values($exam) as $i => $value) {
echo "{$value}<br>";
}
foreach (array_values($exam) as $i => $value) {
echo "// And its mark<br>";
}
Will output this:
First-Term
Second-Term
Third-Term
// And its mark
// And its mark
// And its mark
Will update this answer once I have more details.
Code tested: https://3v4l.org/RDvYN
I would build an array with everything in place and then start to display it:
$exam = array("First-Term","Second-Term", "Third-Term");
$marks = array(1, 2, 3);
$result = array();
foreach (array_values($exam) as $idx => $value) {
$result[] = array(
"exam" => $value,
"mark" => $marks[$idx]
);
}
foreach ($result as $value) {
echo $value['exam'] . "\n";
echo $value['mark'] . "\n\n";
}

Looping into a multidimensional array with PHP

I've got this array:
Array
(
[0] => Array
(
[name] => System
[order] => 1
[icon] => stats.svg
[0] => Array
(
[title] => Multilingual
)
[1] => Array
(
[title] => Coloring
)
[2] => Array
(
[title] => Team work
)
[3] => Array
(
[title] => Tutorials
)
)
)
I want to loop into this to show the section name and after all the features containing in the following array.
So, this is what I made:
foreach ($features as $feature => $info) {
echo '
'.$info['name'].'
<ul class="menu-vertical bullets">
';
foreach (array_values($info) as $i => $key) {
echo '
<li>'.$key['title'].'</li>
';
}
echo '
</ul>
';
}
It works except for the first third <li> where I have the first char of name, order and icon value.
Do you know why ?
Thanks.
array_values return value of array so for info values is name, order, icon, 0, 1, ...
Your values foreach is wrong if you just want print title you can use:
foreach ($features as $feature => $info) {
echo '
'.$info['name'].'
<ul class="menu-vertical bullets">
';
//Remove some keys from info array
$removeKeys = array('name', 'order', 'icon');
$arr = $info;
foreach($removeKeys as $key) {
unset($arr[$key]);
}
foreach (array_values($arr) as $i => $key) {
echo '
<li>'.$key['title'].'</li>
';
}
echo '
</ul>
';
}
In php, array_values means all the values of the array. So array_values($info) is array($info['name'], $info['order'], $info['icon'], $info[0], $info[1], $info[2], $info[3])
in your example, you can skip the non-integer keys of the $info to get your titles:
<?php
$features = array();
$info = array();
$info['name'] = 'System';
$info['order'] = 1;
$info['icon'] = 'stats.svg';
$info[] = array('title'=>'Multilingual');
$info[] = array('title'=>'Coloring');
$features[] = $info;
foreach ($features as $feature => $info) {
echo $info['name'] . PHP_EOL;
echo '<ul class="menu-vertical bullets">' . PHP_EOL;
foreach ($info as $k => $item) {
if(!is_int($k)) continue;
echo '<li>' . $item['title'] . '</li>' . PHP_EOL;
}
echo '</ul>' . PHP_EOL;
}
BUT, your original data structure is not well designed and hard to use. For a better design, you can consider the following code, move your items to a sub array of $info:
<?php
$features = array();
$info = array();
$info['name'] = 'System';
$info['order'] = 1;
$info['icon'] = 'stats.svg';
$info['items'] = array();
$info['items'][] = array('title'=>'Multilingual');
$info['items'][] = array('title'=>'Coloring');
$features[] = $info;
foreach ($features as $feature => $info) {
echo $info['name'] . PHP_EOL;
echo '<ul class="menu-vertical bullets">' . PHP_EOL;
foreach ($info['items'] as $item) {
echo '<li>' . $item['title'] . '</li>' . PHP_EOL;
}
echo '</ul>' . PHP_EOL;
}
Sample output of the two demos:
System
<ul class="menu-vertical bullets">
<li>Multilingual</li>
<li>Coloring</li>
</ul>
It works except for the first third li where I have the first char of name, order and icon value. Do you know why ?
Why you see first chars of the values of 'name', 'order', 'icon'? Let see how PHP works.
Take the first loop as an example: foreach (array_values($info) as $i => $key)
Then $i == 0, $key == 'System'
We know that $key[0] == 'S', $key[1] == 'y', $key[2] == 's', etc.
Then you try to access $key['title'], but the string 'title' is not valid as a string offset, so it is converted to an integer by PHP: intval('title') == 0.
Then $key['title'] == $key[intval('title')] == 'S'
That's what you see.
array_value() returns the values of the array, here you will get the value of the array $info and what I understand is that is not what you need. See details for array_value().
You can check if the key for the $info is an integer. if yes, echo the title. Give this a try.
foreach ($features as $feature => $info) {
echo $info['name'].'<ul class="menu-vertical bullets">';
foreach ($info as $key => $value) {
if (is_int($key)) {
echo '<li>'.$key['title'].'</li>';
}
}
echo '</ul>';
}

PHP Merge Similar Objects In A Multidimensional Array

I have a multidimensional array in PHP, something that looks like:
array(array(Category => Video,
Value => 10.99),
array(Category => Video,
Value => 12.99),
array(Category => Music,
Value => 9.99)
)
and what I would like to do is combine similar categories and output everything into a table, so the output would end up being:
<tr><td>Video</td><td>23.98</td></tr>
<tr><td>Music</td><td>9.99</td></tr>
Any suggestions on how to do this?
EDIT:
I can have these in two different arrays if that would be easier.
A simple loop will do:
$array = [your array];
$result = array();
foreach ($array as $a) {
if (!isset($result[$a['Category']])) {
$result[$a['Category']] = $a['Value'];
} else {
$result[$a['Category']] += $a['Value'];
}
}
foreach ($result as $k => $v) {
echo '<tr><td>' . htmlspecialchars($k) . '</td><td>' . $v . '</td></tr>';
}
$result = array();
foreach ($array as $value) {
if (isset($result[$value['Category']])) {
$result[$value['Category']] += $value['Value'];
} else {
$result[$value['Category']] = $value['Value'];
}
}
foreach ($result as $category => $value) {
print "<tr><td>$category</td><td>$value</td></tr>";
}

PHP — How to determine number of parents of a child array?

I'm not so strong with arrays but I need to determine how to count the number of parents a child array has in order to determine the indenting to display it as an option in a SELECT.
So, if I have this array:
array(
'World'=>array(
'North America'=>array(
'Canada'=>array(
'City'=>'Toronto'
)
)
)
);
How would I go about determining how many parents 'City' has in order to translate that into the number of spaces I want to use as an indent?
Thanks for any help.
EDIT: Let's see if I can explain myself better:
I have this code I'm using to build the OPTIONS list for a SELECT:
function toOptions($array) {
foreach ($array as $key=>$value) {
$html .= "<option value=\"" . $key . "\" >";
$html .= $value['title'];
$html .= "</option>";
if (array_key_exists('children', $value)) {
$html .= toOptions($value['children']);
}
}
return $html;
}
print toOptions($list);
So, I'm trying to determine how to get the number of parents in order to add spaces before the title in this line:
$html .= $value['title'];
Like:
$html .= " " . $value['title'];
But, I'm not sure how to figure out how many spaces to add.
Hopefully this is more clear.
Thanks for any help so far.
$x = array(
'World'=>array(
'North America'=>array(
'Canada'=>array(
'City'=>'Toronto'
)
)
)
);
// This function do something with the key you've found in the array
function visit($name, $depth)
{
echo $name . ' has ' . $depth . ' parents.';
}
// This function visits all the contents aff $array
function find_recursive($array, $depth = 0)
{
if (is_array($array)) {
foreach ($array as $k => $value) {
visit($k, $depth + 1);
find_recursive($array, $depth + 1);
}
}
}
For visiting:
find_recursive($x);
Well. Off the top what you are dealing with is a multi dimensional array.
You could run a count w/ foreach on each level of the array, and use the count number returned +1 for each level the foreach loops through.
I'm not sure if this answers your question, but I am trying to see exactly what it is you are trying to achieve.
As you are already using a recursive function to display that data, you can just extend your function. There is no need to traverse the array more often than one time:
function getWhitespaces($count) {
$result = '';
while($count--) {
$result .= '$nbsp;';
}
return $result;
}
function toOptions($array, $level=0) {
foreach ($array as $key=>$value) {
$html .= "<option value=\"" . $key . "\" >";
$html .= getWhitespaces($level) + $value['title'];
$html .= "</option>";
if (array_key_exists('children', $value)) {
$html .= toOptions($value['children'], $level + 1);
}
}
return $html;
}
print toOptions($list);
Try the following.. Your solution screams for recursion in my mind. Its a bit ugly but it seems to work
$totraverse = array(
'Moon' => array(
'Dark Side' => "Death Valley"
),
'Halley Commet' => "Solar System",
'World' => array(
'North America' => array(
'Canada' => array(
'City' => 'Toronto'
)
), 'South America' => array(
'Argentina' => array(
'City' => 'Toronto'
)
)
)
);
function traverse($totraverse_, $path="", $count=0) {
global $array;
// echo count($totraverse_) . " count\n";
if (!is_array($totraverse_)) {
echo "returning $path and $key\n";
return array($path, $count);
} else {
foreach ($totraverse_ as $key => $val) {
echo "assting $path and $key\n";
$result = traverse($val, $path . "/" . $key, $count + 1);
if($result){
$array[]=$result;
}
}
}
echo false;
}
$array = array();
traverse($totraverse);
foreach($array as $item){
echo "{$item[0]}--->{$item[1]}\n";
}

PHP: get current array key?

$array = (
array('1231415'=>array('foo'=>'bar', 'test'=> 1)),
array('32434'=>array('foo'=>'bar', 'test'=> '0')),
array('123244'=>array('foo'=>'bar', 'test'=> 0)),
array('193928'=>array('foo'=>'bar', 'test'=> 1))
);
I have an array that has (many) random keys, the ID number. I need to test each array within if 'test' = 1, and so I made a foreach loop.
foreach ($array as $sub) {
if ($sub['test'] == '1' ) {
echo 'User: ' . $sub . ' has test = 1';
}
}
This works, but it returns 'User: Array has test = 1'
How on earth to I get which ID number, (that random number) has test=1 in it?
I tried doing $array as $sub=>$value, but for some reason it just makes the foreach not work. Thank you!
Use this foreach syntax instead:
foreach ($array as $key => $sub) {
if ($sub['test'] == '1' ) {
echo 'User: ' . $key . ' has test = 1';
}
}
This assumes that the data is in the form:
$array = array(
'1234' => array('test' => 1),
'5678' => array('test' => 2)
);
If you need to keep your data as it is now, you'll need to use something more like:
foreach ($array as $item) {
list($key, $info) = $item;
if ($info['test'] == 1) {
echo 'User: ' . $key . ' has test = 1';
}
}
There are 2 problems with your code.
1) Your array declaration is slightly messed up. Try this:
$array = array(
'1231415'=>array('foo'=>'bar', 'test'=> 1),
'32434'=>array('foo'=>'bar', 'test'=> 0),
'123244'=>array('foo'=>'bar', 'test'=> 0),
'193928'=>array('foo'=>'bar', 'test'=> 1)
);
2) In your foreach, you're losing the id key. Try this:
foreach ($array as $id => $sub) {
if ($sub['test'] == 1) {
echo "User: " . $id . " has test = 1\n";
}
}
In my test the above outputs:
User: 1231415 has test = 1
User: 193928 has test = 1

Categories