PHP array multidimensional: foreach starting from determinate level - php

I have a multidimensional array that looks like the one below:
Array
(
[results] => Array
(
[0] => Array
(
[hotel_code] => 15ad7a
[checkout] => 2018-04-26
[checkin] => 2018-04-24
[destination_code] => 1c6e0
[products] => Array
.... etc ....
)
[1] => Array
(
[hotel_code] => 193c6c
[checkout] => 2018-04-26
[checkin] => 2018-04-24
[destination_code] => 1c6e0
[products] => Array
.... etc ....
)
Wanting to create a simple pagination of the results, taking from the array 15 records at a time, through the following code I can recover the first 15 records.
$i = 0;
foreach($data['results'] as $key=>$val){
$i++;
$selez_hotel_code = '' . $val['hotel_code'] . '';
if($i == 15) break;
}
Now, how can I get the next 15 values from the array?
I tried to start the foreach directly from record 15, setting it as follows
$i = 0;
foreach($data['results'][14]['hotel_code'] as $val){
$i++;
$selez_hotel_code = '' . $val . '';
if($i == 15) break;
}
but it did not work.

You could use for loop, to specify the start and the end:
$start = 15 ;
$length = 15 ;
$max = count($data['results']);
for ($idx = $start; $idx < $start + $length && $idx < $max; $idx++) {
$val = $data['results'][$idx]['hotel_code'] ;
$selez_hotel_code = $val ;
}
Note that I've added a verification to avoid to loop over the maximum of results ($idx < $max).

You can use $_GET to paginate. Just have a for loop that uses this param if set, 0 if not. Something like this:
$page = isset($_GET['page']) ? intval($_GET['page']) : 0;
for ($i = $page; $i < ($page + 15); $i++) {
// $data['results'][$i] . . .
}
And when clicking on "next page" or whatever you're using, set the page param

Related

Push the output of a for loop into an array

I am trying to push the output of a for loop into an array but I am not being able to do so. Following is the code that I have written:
<?php
$n = 14;
for ($i = 2; $i <= $n; $i++)
{
for ($j = 2; $j <= $n; $j++)
{
if ($i%$j == 0) // if remainder of $i divided by $j is equal to zero, break.
{
break;
}
}
if ($i == $j) //
{
$form = $i;
//echo $form;
$numArray = array();
array_push($numArray, $form); // Here I am trying to push the contents from the `$form` variable into the `$numArray`
print_r($numArray);
}
}
?>
The output that I obtain through this is:
Array ( [0] => 2 ) Array ( [0] => 3 ) Array ( [0] => 5 ) Array ( [0] => 7 ) Array ( [0] => 11 ) Array ( [0] => 13 )
Here, we see that the array index basically remains the same, so it has no scope for future use. So, how can I make this seem like as shown below:
Array ( [0] => 2 ) Array ( [1] => 3 ) Array ( [2] => 5 ) Array ( [3] => 7 ) Array ( [4] => 11 ) Array ( [5] => 13 )
Please note that, $n in the code can be any number less than 101 and greater than 1. Thank you for your precious time put into reading and trying to helping me out. :)
The $numArray should be declared once, not every time in the loop. And you can simply add value to the array by using expression like: $numArray[] = $i;
Try this code:
<?php
$numArray = array();
$n = 14;
for ($i = 2; $i <= $n; $i++) {
for ($j = 2; $j <= $n; $j++) {
if ($i % $j == 0) { // if remainder of $i divided by $j is equal to zero, break.
break;
}
}
if ($i == $j) {
$numArray[] = $i;
}
}
print_r($numArray);

PHP For loop skips the first outcome

I'm trying to fill an array with a for loop. This is done to get the amount of pages a certain book has. but when executing the code, it skips the first object in the array. Can anyone tell me why? (I thought it was because $i starts at 1 instead of 0 but that doesn't seem to change anything)
if(!empty($article['finishing'])){
$numPages = $article['copies'];
$arrayIndexNumber = [];
for($i=1; $i <= $numPages; $i++){
$arrayIndexNumber[] = $i;
}
if(count($arrayIndexNumber) >= 1 ){
if(count($arrayIndexNumber) == 1){
$output['attributes']['EFPageRange'] = 1;
$print_jobs[$article['id']][] = $output;
}
if(count($arrayIndexNumber) > 1){
$comma_separated1 = implode(", ", ['1', $article['copies']]);
$output['attributes']['EFPageRange'] = $comma_separated1;
$print_jobs[$article['id']][] = $output;
}
array_shift($arrayIndexNumber);
array_pop($arrayIndexNumber);
$comma_separated2 = implode(", ", $arrayIndexNumber);
$output['attributes']['EFPageRange'] = $comma_separated2;
if(count($arrayIndexNumber) >= 2){
$print_jobs[$article['id']][] = $output;
}
}
$article['file_url'] = 'i has finishing';
$output['attributes']['username'] = $article['file_url'];
}
above code outputs:
[0] => Array
(
[attributes] => Array
(
[title] => 277569
[EFPrintSize] => a4
[num copies] => 1
[num pages] => 119
[EFPCName] => 80
[EFDuplex] => TopTop
[EFPageRange] => 1, 119
)
)
instead of:
[0] => Array
(
[attributes] => Array
(
[title] => 277564
[EFPrintSize] => a4
[num copies] => 1
[num pages] => 45
[EFPCName] => 80
[EFDuplex] => false
[EFPageRange] => 1, 45
[username] => i has finishing
[EFColorMode] => Grayscale
)
)
Your first array element is deleted because of array_shift:
array_shift($arrayIndexNumber);
array_shift
array_shift — Shift an element off
the beginning of array
Debug your code:
for($i=1; $i <= $numPages; $i++){
$arrayIndexNumber[] = $i;
}
echo '<pre>';
print_r($arrayIndexNumber); // Check what the array returns
php array indexes starts to count from zero
for($i=1; $i <= $numPages; $i++)
^^^
change it to $i=0

Count instances in an array with PHP

I'm trying to get a count of how many instances of 'UnitSqFeet' are within a certain range.
For example how many instances are between 0 - 175, or 176 - 300.
Here is a part example of the array (it contains 46 in total).
Array (
[0] => Array ( [UnitNumber] => 1.03 [UnitSqFeet] => 60.75 )
[1] => Array ( [UnitNumber] => 1.04 [UnitSqFeet] => 160.39 )
[2] => Array ( [UnitNumber] => 1.05 [UnitSqFeet] => 231.55 )
[3] => Array ( [UnitNumber] => 1.06 [UnitSqFeet] => 280.24 )
)
The 'UnitSqFeet' is a string so I'm assuming it'll have to be converted somewhere in there.
I managed to get this working as below but it would only output this in the first cell of an html table and not the rest. After doing some research on here I understand it's because I was repeating the query for every cell and after the first it had already retrieved all the rows. Not sure if there's a solution whereby I can just reset the query?
$counter = 0;
while ($units = odbc_fetch_array($result)) {
$num = $units['UnitSqFeet'];
$float = (float)$num;
if ($float > 0 && $float < 175) {
count($float);
$counter++;
};
};
echo $counter;
Try as
$count = $count2 = 0;
$result = array();
foreach(array_column($arr,'UnitSqFeet') as $key => $value){
if(round($value) <= 170){
if(!isset($result['0-170'])) $result['0-170'] = $count++;
$result['0-170'] = $count++;
}else{
if(!isset($result['171-300'])) $result['171-300'] = $count2++;
$result['171-300'] = $count2++;
}
}
print_r($result);
Fiddle
Try it here: http://viper-7.com/ofozYB
<?php
$UnitSqFeet = array_column($array, 'UnitSqFeet');
$output = array_filter($UnitSqFeet, function ($var) {
return ( $var >= 70 && $var <= 250 ); // return if between 70 & 250
});
print_r($output);
echo "There is " . count($output) . " values in the selected range";

How do I create arrays within a nested for loop in PHP

I want to create an array from this nested for loop
for($i = 0; $i < 2; $i++){
for($j = 0; $j < 3; $j++){
$dis = $i + $j;
createArr($dis, $i);
}
echoArr($i);
}
To do this I created a function called createArr() which receives $dis and the $i iterator.
$arr= array();
function createArr($dis, $i){
$arr= 'arr'.$i;
array_push($arr, $dis);
return $arr;
}
I want $arr to be the name of the array in this example during the first iteration of the nested for loop $i = 0. Thus I want the name of the array to be $arr0 with the array_push function pushing all the elements of $j while $i = 0 then to store into another array when the second iteration of $i when it starts at$arr1 to push the new elements of this array within $j's iteration when $i = 1;
function echoArr($i){
$arr= 'arr'.$i;
return $arr;
}
this last function is to echo the finished array after an iteration of $i is done.
I am not sure what you are expecting
$arr= 'arr'.$i;
array_push($arr, $dis);
to do, but array_push expects first parameter to be array,
but as you can see $arr is a string.
Is this what you need?
$arr = array();
for($i = 0; $i < 2; $i++){
for($j = 0; $j < 3; $j++){
$dis = $i + $j;
array_push($arr, createArr($dis, $i));
}
echoArr($i);
}
function createArr($dis, $i){
return array('arr'.$i => $dis);
}
print_r($arr);
//prints: Array ( [0] => Array ( [arr0] => 0 ) [1] => Array ( [arr0] => 1 ) [2] => Array ( [arr0] => 2 ) [3] => Array ( [arr1] => 1 ) [4] => Array ( [arr1] => 2 ) [5] => Array ( [arr1] => 3 ) )
What are you trying to achieve?
For the future pls describe what you would like to achieve so we can help you achieve it better.
Let me start with the first piece of code
You would like to echo the array. You are just echoing the column.
why build your own function to add something to an array?
and if you to do something with the return
$myarray[$i] = createArr($key,$value); //not a good solution, just for explaining.
Since I don't know what you like to achieve here an example of an array loop
$myarray = array();
for($i = 0; $i < 2; $i++){
for($j = 0; $j < 3; $j++){
$dis = $i + $j;
$myarray[$i][$j] = 'row:' . $i . ' column' . $j;
}
}
var_dump($myarray);
and the dump
array (size=2)
0 =>
array (size=3)
0 => string 'row:0 column0' (length=13)
1 => string 'row:0 column1' (length=13)
2 => string 'row:0 column2' (length=13)
1 =>
array (size=3)
0 => string 'row:1 column0' (length=13)
1 => string 'row:1 column1' (length=13)
2 => string 'row:1 column2' (length=13)

After for-loop, returned array is wrong

I have something like that:
$n = 2;
$items = array();
$result = array(); // new array with random items
$random_items = array_rand( $items, $n );
for( $f=0; $f<=$n; $f++ ) {
$result[] = $items[$random_items[$f]];
}
$items is sth like
Array ( [0] => file1.jpg [1] => file2.png [2] => file3.jpg ... and so on )
This is working OK... but if I set $n to 1 then the script is not working or working incorrectly!
If $n == 2 (or more) the result array have last element's value empty
Array ( [0] => 20141125-17826a4b34.png [1] => 20141125-27fe57561d.jpg [2] => )
If $n == 1 (exactly) the result array is like
Array ( [0] => [1] => )
The result array should be the same format as items array but only with $n random items.
Thanks in advance!
Working
if( $n > 1 ) {
for( $f=0; $f<$n; $f++ ) {
$result[] = $items[$random_items[$f]];
}
}
elseif( $n == 1 ) {
$result[0] = $items[$random_items];
}
You should $f < $n instead of $f <= $n
for( $f=0; $f < $n; $f++ ) {
$result[] = $items[$random_items[$f]];
}
Because, when you're using $f <= $n its running up to 0,1 (when, $n = 1) OR 0,1,2 (when $n = 2) and you're missing the last indexed element.
When picking only one entry, array_rand() returns the key for a random
entry(not array).Otherwise, an array of keys for the random entries is returned.
So, This means, when you're using $n = 1, then $random_items is just a value(not array). eg.
for $n = 1, $random_items = 4;
but for $n >= 2, $random_items = [1, 6, 3, 6];

Categories