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()
Related
I've got an array containing
"1", "2", "3", "4"
And I use array_rand to select one of those numbers randomly five times. Then I want to count how many of the result of array_rand that have been chosen multiple times like the number 2 got chosen 2 times and number 3 got chosen 2 times.
I have tested doing this
$array = array($kort1[$rand_kort1[0]], $kort1[$rand_kort2[0]], $kort1[$rand_kort3[0]], $kort1[$rand_kort4[0]], $kort1[$rand_kort5[0]]);
$bank = array_count_values($array);
if (in_array("2", $bank)) {
echo "You got one pair";
} elseif(in_array("2", $bank) && (???)) {
echo "You got two pair";
}
it will tell me "You got one pair" if one of those numbers were randomly chosen 2 times but my problem is I don't know how to make it say "You got two pairs" if 2 of those numbers were chosen 2 times.
the result of $bank could be
[4] => 1 [3] => 2 [1] => 2
Try this: (This will work even if your array has more than 4 values)
$count = 0;
foreach ($bank as $key=>$value) {
if ($value === 2) {
$count++;
}
}
if ($count) {
$s = $count > 1 ? 's' : '';
echo "You got $count pair$s";
}
It will show an output like You got 1 pair. If you want to use words (like you mentioned in your question), you can use NumberFormatter class
You can use array_filter to appy a function to each element of your array
$bank=array(4 => 1, 3 => 2, 1 => 2); // Your array
function pairs($var) {
return($var === 2); // returns value if the input integer equals 2
}
$pairs=count(array_filter($bank, "pairs")); // Apply the function to all elements of the array and get the number of times 2 was found
if ($pairs === 1)
{
echo "you got one pair";
}
if ($pairs === 2) {
echo "you got two pairs";
}
EDIT
Thought of this one liner later:
$pairs=count(array_diff($bank, array(1,3,4)));
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>";
}
I'm working on an algorithm to calculate the amount of levels in an array of arrays.
The reason I need this is because I need to fetch a list of categories from the database that belongs to a category parent, and depending of the amount of levels this array has, I need to display an amount of category lists (to select categories).
So it would be a category list for each level of categories, for example
Vehicles
Cars
honda
Red
Blue
Yellow
ford
Red
suzuki
Red
Green
BMW
Motorcycles
bla bla
bla bla
Groceries
Fruits
Berries
Red
Strawberries
So I need a function to check the amount of levels of the selected parent, for example if i pass the ID of vehicles i want it to return 4 or 3 if we count Vehicles as level 0, so I know that if the client selected Vechicles from the first list I will have to display 3 more lists.
So far, what I have that is not working is
function count_children_level($list_of_children, $start_depth = 0){
// if the data being passed is an array
if(is_array($list_of_children)){
// amount of nodes is equal to the
$max = $start_depth;
foreach($list_of_children as $i){
$result = count_children_level($i, $start_depth + 1);
if ($result > $max){
$max = $result;
}
}
return $max;
}
//if is not array
else {
return $start_depth;
}
}
I really need to understand how this works because i have to work with several functions like this one, so please if you can, explain your answer in detail.
Thanks
The depth of a nested array is equal to the depth of the largest array in it + 1.
So for your recursive function, instead of passing the entire array every time, you can make an actual recursive call that only gets the depth of the sub-array. So this function returns 1 for a normal, flat array and 1 extra for each level.
<?php
function array_depth($array) {
// Determine largest sub-array. Start with 0 if there are no arrays at all.
$max = 0;
foreach ($array as $item) {
if (is_array($item)) {
// Make the recursive call, passing not $array, but the sub-array ($item)
// to the function again.
$depth = array_depth($item);
if ($depth > $max)
$max = $depth;
}
}
// Depth of this array is the depth of the largest sub-array + 1.
return $max + 1;
}
I called it like this:
echo array_depth(
array('x' =>
array('y' =>
array('z')))); // Returns 3.
My interpretation of what #GolezTrol said in their answer ("The depth of a nested array is equal to the depth of the largest array in it + 1"):
function array_depth($a)
{
// If $a is not an array or it's an empty array then its depth is 1
if (! is_array($a) || count($a) == 0) {
return 0;
}
// Otherwise, add 1 to the maximum depth of the elements it contains
return 1 + max(array_map('array_depth', $a));
}
Another solution with the RecursiveIteratorIterator class. In this way you don't need a recursive function:
$array = array(
'Vehicles' => array(
'Cars' => array(
'honda' => array(
'Red',
'Blue',
'Yellow',
)
)
)
);
function getTotalDepth($array) {
$iterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator($array)
);
$max = 0;
foreach ($iterator as $element) {
if (!$iterator->callHasChildren()) {
$max = max($max, $iterator->getDepth());
}
}
return $max;
}
echo getTotalDepth($array);
Also very helpful if you want to iterate the complete array:
$iterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator($array),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($iterator as $element) {
print_r($element);
echo '<br>';
}
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?
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.