PHP For loop skips the first outcome - php

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

Related

How to decrease value by designed order. For loop seems to break in the middle

I would like to make a function that decreases values of an array by specific order.
the values should be decreased by order noodle -> bread -> rice.
I tried to make the function below.
But it does not work well.
the loop break before achiving array_sum($stapleArray) ===$sizeDayArray.
$stapleArray
should be deducted until the total size equals $sizeDayArray
E.g.
input
targetWeekDayArrayArray
(
[0] => tue
[1] => wed
[2] => fri
[3] => sat
)
*size = 4
$sizeDayArray = size_of($targetWeekDayArrayArray)
$stapleArray=
Array
(
[rice] => 5
[bread] => 0
[noodle] => 1
)
expected result
$stapleArray=
Array
(
[rice] => 4
[bread] => 0
[noodle] => 0
)
caller
$differenceSettingAndDay = array_sum($stapleArray)- sizeof($targetWeekDayArray);
$size = sizeof($targetWeekDayArray);
$stapleArray= $this->substractStapleFood($differenceSettingAndDay,$stapleArray, $size);
private function substractStapleFood($substractionnumber,$stapleArray,$sizeDayArray)
{
$array_key = ['noodle','bread','rice'];
for($i = 0; array_sum($stapleArray) ===$sizeDayArray ; $i++ )
{
$i_mod = $i % count($stapleArray); //$i % 3
$key = $array_key[$i_mod];
if (isset($stapleArray[$key]) && $stapleArray[$key] > 0) {
$stapleArray[$key]--;
}
}
return $stapleArray;
}
Actual result
Array
(
[rice] => 5
[bread] => 0
[noodle] => 1
)
It seems that id did not go through the loop.
Wrong in line :
for($i = 0; array_sum($stapleArray) ===$sizeDayArray ; $i++ )
condition array_sum($stapleArray) ===$sizeDayArray start is false => loop is not running
Change same as :
for($i = 0; !(array_sum($stapleArray) ===$sizeDayArray) ; $i++ )

Create an array from two array PHP

i have two arrays
$value_array = array('50','40','30','20','10');
$customer = array('300','200','100');
i want to distribute the value array to customers based on the value of customers that is taken as limit.adding values by checking it wont cross the limit that is 300 , 200 and 100.
but customer array not working one direction it should work first forward and then backward like that
i want to produce an array in form of
Array
(
[0] => Array
(
[0] => 50
)
[1] => Array
(
[0] => 40
[1] => 10
)
[2] => Array
(
[0] => 30
[1] => 20
)
)
After completing customer loop first time it should start from last to first. both array count will change , i mean count.
value array should check 50 -> 300 , 40->200, 30->100 then from last ie, 20 ->100, 10->200 etc.
I tried like
$i = 0;
while($i < count($customer)){
foreach($value_array as $k=>$value){
$v = 0;
if($value <= $customer[$i]){
$customer2[$i][] = $value;
unset($value_array[$k]);
$v = 1;
}
if($v ==1){
break;
}
}
//echo $i."<br/>";
if($i == (count($customer)-1) && (!empty($value_array))){
$i = 0;
$customer = array_reverse($customer, true);
}
$i++;
}
echo "<pre>";
print_r($customer2);
$valueArray = array('50','40','30','20','10','0','-11');
$customer = array('300','200','100');
function parse(array $valueArr, array $customerArr)
{
$customerCount = count($customerArr);
$chunkedValueArr = array_chunk($valueArr, $customerCount);
$temp = array_fill(0, $customerCount, array());
$i = 0;
foreach ($chunkedValueArr as $item) {
foreach ($item as $key => $value) {
$temp[$key][] = $value;
}
$temp = rotateArray($temp);
$i++;
}
// if $i is odd
if ($i & 1) {
$temp = rotateArray($temp);
}
return $temp;
}
function rotateArray(array $arr)
{
$rotatedArr = array();
//set the pointer to the last element and add it to the second array
array_push($rotatedArr, end($arr));
//while we have items, get the previous item and add it to the second array
for($i=0; $i<sizeof($arr)-1; $i++){
array_push($rotatedArr, prev($arr));
}
return $rotatedArr;
}
print_r(parse($valueArray, $customer));
returns:
Array
(
[0] => Array
(
[0] => 50
[1] => 0
[2] => -11
)
[1] => Array
(
[0] => 40
[1] => 10
)
[2] => Array
(
[0] => 30
[1] => 20
)
)

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";

Group array into sub arrays of 2 elements, last group missing

I fetch data from my database and it returns 6 rows. I loop over them add them to a temporary array and then every 2 iterations I add them to a parent array so I will know have an array with sub arrays grouped by 2. Below, as you can see, I echo out each iteration for 6 results. My grouped array is only showing 2 groups of 2 when it should be 3 groups of 2. What am I doing wrong?
Note: I checked the data and the first 2 groups are correct data, but the last 2 rows are missing.
// group entries into subgroups of 2
$buffer = array();
$entries = array();
for( $i = 0; $i < $journal_entries_count; $i++ )
{
if( $i % 2 == 0 && $i > 0 )
{
$entries[] = $buffer;
unset( $buffer );
$buffer = array();
}
$buffer[] = $journal_entries[ $i ];
echo $i, '<br />';
}
0
1
2
3
4
5
Array
(
[0] => Array
(
[0] => Array
(
[journal_entry_id] => 196
[journal_entry_date] => 2014-10-24 20:01:44
[scoring_type_id] => 1
[score] => 2662.00
[wod_title] => yyyyy
[wod_date] => 2014-09-12
[strength] =>
[repscheme] =>
[benchmark] => Annie
)
[1] => Array
(
[journal_entry_id] => 197
[journal_entry_date] => 2014-10-24 20:01:44
[scoring_type_id] => 1
[score] => 196.00
[wod_title] => yyyyy
[wod_date] => 2014-09-12
[strength] =>
[repscheme] =>
[benchmark] => Badger
)
)
[1] => Array
(
[0] => Array
(
[journal_entry_id] => 195
[journal_entry_date] => 2014-10-24 20:00:19
[scoring_type_id] => 1
[score] => 300.00
[wod_title] => Koala Bear WOD
[wod_date] => 2014-10-21
[strength] =>
[repscheme] =>
[benchmark] => Amanda
)
[1] => Array
(
[journal_entry_id] => 194
[journal_entry_date] => 2014-10-24 20:00:19
[scoring_type_id] => 7
[score] => 5.20
[wod_title] => Koala Bear WOD
[wod_date] => 2014-10-21
[strength] => Back Squat
[repscheme] => 10RM
[benchmark] =>
)
)
)
Solution?
I'm not marking it as a solution yet because I'm not sure it will work in all cases,
but loop at each iteration it never hits the last one.
0 = skip - add
1 = skip - add
2 = add - add
3 = skip - add
4 = add - add
5 = skip - add
I added $journal_entries_count + 1 and the results are now correct.
Thoughts?
If $journal_entries_count is 6, then at the end of your loop, $buffer will contain two rows, but it won't have been added to $entries.
You need to add a final
$entries[] = $buffer;
after the loop. Alternatively, you could use array_chunk:
$entries = array_chunk($journal_entries, 2);
can you try it with some simpler code like this and see how you go.
$entries = array();
$journal_entries[] = 1;
$journal_entries[] = 2;
$journal_entries[] = 3;
$journal_entries[] = 4;
$journal_entries[] = 5;
while (count($journal_entries)){
$entries[] = array_slice($journal_entries,0,2);
$journal_entries = array_slice($journal_entries,2);
}
print_r($entries);
You are missing the last 2 entries because you don't add the buffer from the last loop.
You need to update your code and after the foreach loop, check if the buffer is empty or not. If it's not empty then add it to the final array.
You say that for $journal_entries_count + 1 it works, because you actually run the loop one more time and adds the final buffer from the "true" last loop.
The end code should be something like this:
$buffer = array();
$entries = array();
for( $i = 0; $i < $journal_entries_count; $i++ ) {
if( $i % 2 == 0 && $i > 0 ) {
$entries[] = $buffer;
unset( $buffer );
$buffer = array();
}
$buffer[] = $journal_entries[ $i ];
echo $i, '<br />';
}
// add any leftover buffer data
if(count($buffer) > 0) {
$entries[] = $buffer;
}

Multi array iteration

Hi i have a function which is:
public function getpopularAction()
{
$businessReviewMapper = new Application_Model_Mapper_BusinessReviewsMapper();
$result = $businessReviewMapper->getTotalPopular();
for ($i = 0; $i < count($result); $i++)
{
$rotd[$i] = $businessReviewMapper->getROTD($result[$i]['review_id']);
for ($j = 0; $j < count($rotd); $j++)
{
$rotd[$j]['u_img'] = $this->view->getLoginUserImage(
$rotd[$j]['social_id'], $rotd[$j]['login_type'], null, null, large
);
}
}
print_r($rotd);
exit;
}
The result i get is:
Array
(
[0] => Array
(
[0] => Array
(
[review_id] => 161
[review_desc] => tgi goooood....................
[user_id] => 2
[rating] => 3
[review_date] => 20121022203529
[name] => zlippr
[social_id] => 12345678
[login_type] => facebook
[user_unique_name] => zlippr
[city] => Kuala Lumpur
[business_name] => TGI Friday Kuala Lumpur
)
[u_img] => /public/images/image_not_found.png
)
)
I do not know where problem is but the u_img is not fetched properly, not sure whether the array loop is execute properly.
Not sure what the inner loop is for. If you are trying to retrieve the loginuserimage corresponding to each rotd, you need to do like :
for ($i = 0; $i < count($result); $i++)
{
$rotd[$i] = $businessReviewMapper->getROTD($result[$i]['review_id']);
$rotd[$i]['u_img'] = $this->view->getLoginUserImage(
$rotd[$i]['social_id'],$rotd[$i]['login_type'],null,null,large);
}
By looking at your ouput, your result are inside 2nd layer of array which means you should replace your variable inside getLoginUserImage from
$rotd[$i]['social_id'],$rotd[$i]['login_type']
to
$rotd[$i][0]['social_id'],$rotd[$i][0]['login_type']

Categories