For loop with foreach loop in it? PHP - php

I am trying to make the following happen.
Go through a for loop and produce a set of 7 select boxes with time options in them. I have this loop working fine right now. This is for a form with times for start of an event for each day of the week.
On user wanting to change the values, I would like to produce the same 7 boxes however foreach of the values entered in the database I would like to add the original selected value for that date, and provide the please select value for the of the boxes.
foreach loop for the times
foreach ($times as $time) {
echo '<option value="' . $time['num'] . '"'; if ($event == $time['dec']){echo 'selected="selected"';};
echo '>';
echo $time['clock'];
echo '</option>';
}
Times Array
$times = array( array('num' => 70000, 'dec' => '07:00:00', 'clock' => '7:00am'), array('num' => 71500, 'dec' => '07:15:00', 'clock' => '7:15am') etc…
This produces the select options.
Then the foreach to get the existing values.
foreach ($event -> Selected as $select) {
$event = $select -> Start;
}
This is all working right now but only produces say 3 selects if 3 records exist, I would like to produce 7 selects with the first 3 selects with the DB value, if 3 records exist and 4 empty selects

The array contains only a limited number of entries, so the loop will iterate only up to this number.
You can work around this by checking how many elments are in the array, and outputting empty values for the rest.
for example add the following after the loop:
$count = 7 - count($times);
for($i = 0; $i < $count; $i ++)
{
echo '<option></option>';
}
The above is a simple loop that outputs empty entries to ensure there are 7 drop down values.

You can do this before your foreach:
$desired = 7;
$extra = array_fill(0, $desired - count($times));
$times = array_merge($times, $extra);
It will make your array $times to be always as long as the number in $desired.

Related

How to add the values from a foreach loop php

I have and foreach loop that outputs the totals I want to add when i echo the $val_tex it outputs in one number like "4911165" but if I echo it with a break tag it gives me the right values. It looks like
49
1
1
1
65
My question is how to get the sum of all the values which should equal "117"
$val_tex = array();
foreach ( $get_seller as $keys ) {
$val_tex = $keys['total'];
}
You have to add them together in the foreach loop - there's a simple way to do that $total += $keys['total']; It's just a simpler way of saying $total = $total + $keys['total'];
There are also other ways - $total = array_sum(array(1,2,3,4)); // == 10 for example. To get the sum from a single column, you get an array that only contains the values from the specific column first:
// an array of the values from that column
$arrayTotall = array_column($keys, 'total');
$total = array_sum($arrayTotals);
Your for each needs another variable to add them:
foreach ( $get_seller as $keys ) {
$val_tex = $keys['total'];
$sum = += $val_tex
//or...
$val_tex += $keys['total'];
//depending on how you want to us val_tex
}
The .= adds the value to previous value instead of overwriting it.

How to display data from multidimensional array in php

I have some issues displaying the data from my multidimensional array. Is a 3 array combined in 1.
I have combined the arrays like this:
$sums = array_merge(array($titlu), array($dimensiune), array($datalink));
Now, the code that I am using to display the array, is:
for($r=0;$r<count($sums);$r++)
{
for($c=0;$c<count($sums[$r]);$c++)
{
echo $sums[$r][$c]."<br />";
}
echo "<br />";
}
But this displays like:
$sums[0][0]
$sums[1][0]
$sums[2][0]
$sums[0][1]
$sums[1][1]
$sums[2][1]
and so on...
Above example with or without the new line, outputs every array one at a time.
What I need to show is to combine the data from the arrays like position 0 from array 0 with position 0 from array 1 and position 0 from array 3, like this:
$sums[0][0] ... $sums[1][0] ... $sums[2][0]
$sums[0][1] ... $sums[1][1] ... $sums[2][1]
and so on...
So everytime the first value is fixed, like 0, 1 and 2... and the other one can go from 1 to X, those being the entries i want to put in my database
How can I achieve this?
Thank you guys.
If you want to print all the $sums[$r][0] elements, then all the $sums[$r][1] elements, and so on, you need to rearrange the loops. You have to iterate over column numbers in the outer loop, then over rows in inner loop.
$colcount = count($sums[0]);
for ($c = 0; $c < $colcount; $c++) {
foreach ($sums as $row) {
echo $row[$c] . " ";
}
echo "<br>";
}

Searching an array of objects for specific key value pairs

After pulling in some data from a mysql database saving it to a variable, I'm wondering if it's possible to "query" the variable instead of doing another request to the database? I realise I need to search an array of objects based on key and value. So here is an example of what I have.
<?php
[{"customer":1,"item":1,"bought_at":"2016-12-15 11:41:11"},
{"customer":2,"item":1,"bought_at":"2016-12-15 11:43:21"},
{"customer":3,"item":1,"bought_at":"2016-12-16 13:31:11"},
{"customer":1,"item":2,"bought_at":"2016-12-16 12:12:21"},
{"customer":1,"item":3,"bought_at":"2016-12-17 15:13:58"}]
?>
So lets say I need to search it based on the item number and the date (but not time) when the item was bought. The next step would be to return the result as another array of objects. So if I were to search for item 1 bought at 2016-12-15 it would return.
[{"customer":1,"item":1,"bought_at":"2016-12-15 11:41:11"},
{"customer":2,"item":1,"bought_at":"2016-12-15 11:41:21"},]
Is this possible? If so how would I go about doing it?
Regards
EDIT: The reason I originally asked this question was because I had a query inside a nested foreach loop which bothered me. It's a piece of code that builds up a a json table at the back-end to pass information to the front end to draw a google line graph. Also I changed the data slightly in my original question to try to make it easier to read. It's also built in Laravel. The complete code is pretty large so I'm just posting the nested foreach loops. The query is in the second loop and is given the variable $activations.
foreach ($timeRange as $time){
$temp = array();
$timeTwentyFour = date("G", strtotime($time));
$temp[] = array('v' => "Date(01,01,2000,$timeTwentyFour)");
foreach($data as $row){
$count = 0;
$activations = DB::table('customer_display')->where('display_id',$row->id)->where(DB::raw('DATE(created_at)'),$day)->get();
foreach($activations as $activation){
$timestamp = $activation->created_at;
$activationTime = explode(" ", $timestamp)[1];
if (strtotime($activationTime) >= strtotime($time) && strtotime($activationTime) < strtotime($time) + 3600){
$count++;
};
}
$temp[] = array('v' => (float) $count);
//The custom tooltip
$temp[] = array('v' => $time . ' ' . $row->location . '. ' . $count . ($count == 1 ? ' Activation' : ' Activations'));
}
$rows[] = array('c' => $temp);
}
If those are objects in an array and you only wanted the entries where item is 1 you could use array_filter;
$filtered = array_filter($items, function($item){
// only return objects where this is true
return $item->item == 1;
});
If you wanted only items purchased on the 15th use
return date('d', strtotime($item->bought_at)) == 15;
and if you want to see items 1 bought on the 15th you'd use
$filtered = array_filter($items, function($item){
return $item->item === 1
&& date('d', strtotime($item->bought_at)) == 15;
});
Also check out this answer on comparing dates for more information on how to better do that.
Another database request will be the better approach in most cases. A database is optimized for querying data. It can use indexes, etc. Well known databases like MySQL have a query optimalisation. Doing it by hand will be less efficient.
First downloading too much data and then use something like array_filter to linearly search through all the data is far less efficient than just querying the data with the search criteria in the query.
One way to do it is:
//Prepare statement once
$statement = $pdo->prepare("SELECT * FROM table WHERE item = ? AND bought_at = ?");
$statement->execute(array(1, "2016-12-15"));
foreach ($statement->fetchAll() as $array)
//Do something with $array
//reuse prepared statement with another selection criteria
$statement->execute(array(3, "2016-12-16"));
foreach ($statement->fetchAll() as $array)
//Do something with $array

php array insert and print

This is a part of my PHP program.
//for example: $rec_count = 30
$totalpages=(int)$rec_count/10;
$index=0;
$pageslink[$totalpages]='';
while($index <= $totalpages ){
$pageslink['index']=$index;
echo '<br>Index: '.$index.'<br>';
echo '<br>Page '.$pageslink['index'].' ';
$index++;
}
print_r($pageslink);
It comes out like this:
Index: 0
Page 0
Index: 1
Page 1
Index: 2
Page 2
Index: 3
Page 3 Array ( [3] => [index] => 3 )
Its supposed to be pageslink[0] = 1; pageslink[1 ]= 2; pageslink[3] = 3; But When I print_r() the pageslink array , only 3 as a value. I've been trying to find out why only 3 is inserted as value in array.
I am a beginner, so thank you in advance for your help. It will be much appreciated.
In the short version of this answer, arrays in PHP start counting from 0, not 1. So on the first loop it would be 0 and the second loop it would be 1 and so on.
You're using
$pageslink['index'] = $index;
Meaning you set the item with the named key 'index' in your array to the value of your variable $index, instead of using $index as your key.
In PHP (and many other languages) you can refer to an item in an array with its index number (0, 1, 2, etc.) or by a word (named key).
For example:
$myArray = ['John', 'London'];
echo $myArray[0]; // John
echo $myAray[1]; // London
or
$myArray = ['name' => 'John', 'city' => 'london'];
echo $myArray['name']; // John
echo $myArray['city']; // London
What you are doing now is setting the same item in your array (the item you're calling index) to a new value every loop, overwriting its old value. So after all the loops you'll only have the last value saved.
You want something like this:
$pageslink[$index] = $index + 1;
Which will translate to:
$pageslink[0] = 1; // first loop
$pageslink[1] = 2; // second loop
$pageslink[2] = 3; // third loop
By the way, a for loop would be cleaner in your example code:
$rec_count = 30
$totalpages=(int)$rec_count/10;
$pageslink = array(); // this is how to create an array, not with ''
for($i=0;i<$totalpages;$i++){
$pageslink[] = $i;
}
print_r($pageslink);
You over complicate the code here, try:
$totalpages=(int)$rec_count/10;
$index=0;
$pageslink = array();
while($index <= $totalpages ){
$pageslink[]=$index+1;
echo '<br>Index: '.$index.'<br>';
echo '<br>Page '.$pageslink[$index].' ';
$index++;
}
print_r($pageslink);
But this code is very weird. You just create array of n elements.
Could you explain what do you try to achieve here?

Use Multidimensional Array within a For Loop in PHP

I have the following multidimensional array:
<? $array = array(0 => 2, 3 => 1, 5 => 1 );
Which looks like this when printed:
Array ( [0] => 2 [3] => 1 [5] => 1 ); //the value in brackets is the shoe size
The first part of array is a "shoe size", and the second part of the array is the number available in inventory.
I am trying to print out a table that lists all shoe sizes (even if not in the array), and then loop through to provide "number available" in inventory.
Here's what I have so far, but isn't working:
<?php
$array = array(0 => 2, 3 => 1, 5 => 1 );
print ('<table>');
print ('<thead><tr><th>Shoe Size</th>');
for ($i=3; $i<=12; $i += .50) {
print ('<th>'.$i.'</th>');
}
print('</tr></thead>');
print('<tbody><td>Total</td>');
foreach ($array as $shoe_size=>$number_in_inventory) {
for ($i=3; $i<=12; $i += .50) {
if ($i == $shoe_size) {
print('<td>'.$number_in_inventory.'</td>');
}
else {
print('<td>0</td>');
}
}
}
print("</tbody></table>");
My problem is, because I have a foreach loop AND a for loop, it is printing out twice the number of table columns (<td>'s).
How can I better adjust this code so that it only loops through and correctly displays the columns once? I am pretty lost on this one.
Many thanks!
Change your main loop to go through each possible shoe size; if the size exists in the inventory array ($array) then print that value, else print zero.
// ...
print('<tbody><td>Total</td>');
for ($i = 3; $i <= 12; $i += .50) {
if (array_key_exists("$i", $array)) {
print '<td>'.$array["$i"].'</td>';
} else {
print '<td>0</td>';
}
}
// ...
My problem is, because I have a foreach loop AND a for loop, it is printing out twice the number of table columns ('s).
That is precisely the problem. Just like with the <th> section, you want to print a <td> for each of the possible shoe sizes (3 through 12). For each possible shoe size, all you need to do is check to see whether there is a corresponding value in the inventory as my snippet above does.
You might try looping through all the sizes and then for each size, check to see if it's in the array using array_key_exists()

Categories