Can't push all array items into a second array PHP - php
So I have an array ($items) which has about 900 items in it. What I'm trying to do is, for the items that are read ($key["status"] == 1) which is about 300 items -> push those into a second array ($lifeSpanArray) with two attributes (added_date and read_date).
For some reason, when I try to push items into the lifespan array, I only have one item. Like I said, there are around 300 items that are status read - and I can dump those out, so I believe I am making a mistake with building my lifeSpanArray and pushing into it.
Any help much appreciated!
$items = $pocket->retrieve($params, $accessToken);
$numberArticles = count($items["list"]);
$hasRead = 0;
$hasNotRead = 0;
$readDatesArray = array();
$lifeSpanArray = array();
foreach ($items['list'] as $key) {
if ($key["status"] == 1) {
$hasRead++;
$timeAdded = date('m/d/Y', $key["time_added"]);
$dateRead = date('m/d/Y', $key["time_read"]);
// Where the problem is - only one item added
$lifeSpanArray['timeAdded'] = $timeAdded;
$lifeSpanArray['timeRead'] = $dateRead;
//Push into the read dates array
array_push($readDatesArray, $dateRead);
}
else {
$hasNotRead++;
}
}
var_dump($lifeSpanArray);
As you are overwriting your $lifeSpanArray array on each iteration you're must be getting only last entry so what you need is a two-dimension array,
Change this,
//Push into lifespan array
$lifeSpanArray['timeAdded'] = $timeAdded;
$lifeSpanArray['timeRead'] = $dateRead;
to,
$lifeSpanArray[] = array('timeAdded' => $timeAdded,'timeRead' => $dateRead);
$lifeSpanArray['timeAdded'] = $timeAdded;
$lifeSpanArray['timeRead'] = $dateRead;
For the above code, you are actually assigning a scalar value to $lifeSpanArray['timeAdded'] and $lifeSpanArray['timeRead'].
To treat them as array and push values to them, you should first initialize timeAdded and timeRead as arrays first:
$lifeSpanArray = array(
'timeAdded' => array(),
'timeRead' => array()
);
And pushing values to them within the foreach loop:
$lifeSpanArray['timeAdded'][] = $timeAdded;
$lifeSpanArray['timeRead'][] = $dateRead;
Related
Looking for an element in an array in PHP
I don't know if I'm managing this array in the best way. The array I have is this: $bass = $_POST['bass']; $selected_scale = $_POST['scale']; $major_scales = array ( array("C","D","E","F","G","A","B","C","D","E","F","G","A","B",), array("C#","D#","E#","F#","G#","A#","B#","C#","D#","E#","F#","G#","A#","B#",), array("Db","Eb","F","Gb","Ab","Bb","C","Db","Eb","F","Gb","Ab","Bb","C",), array("D","E","F#","G","A","B","C#","D","E","F#","G","A","B","C#"), array("D#","E#","F##","G#","A#","B#","C##","D#","E#","F##","G#","A#","B#","C##"), array("Eb","F","G","Ab","Bb","C","D","Eb","F","G","Ab","Bb","C","D"), array("E","F#","G#","A","B","C#","D#","E","F#","G#","A","B","C#","D#"), array("E#","F##","G##","A#","B#","C##","D##","E#","F##","G##","A#","B#","C##","D##"), array("Fb","Gb","Ab","Bbb","Cb","Db","Eb","Fb","Gb","Ab","Bbb","Cb","Db","Eb"), array("F","G","A","Bb","C","D","E","F","G","A","Bb","C","D","E"), array("F#","G#","A#","B","C#","D#","E#","F#","G#","A#","B","C#","D#","E#"), array("Gb","Ab","Bb","Cb","Db","Eb","F","Gb","Ab","Bb","Cb","Db","Eb","F"), array("G","A","B","C","D","E","F#","G","A","B","C","D","E","F#"), array("G#","A#","B#","C#","D#","E#","F##","G#","A#","B#","C#","D#","E#","F##"), array("Ab","Bb","C","Db","Eb","F","G","Ab","Bb","C","Db","Eb","F","G"), array("A","B","C#","D","E","F#","G#","A","B","C#","D","E","F#","G#"), array("A#","B#","C##","D#","E#","F##","G##","A#","B#","C##","D#","E#","F##","G##"), array("Bb","C","D","Eb","F","G","A","Bb","C","D","Eb","F","G","A"), array("B","C#","D#","E","F#","G#","A#","B","C#","D#","E","F#","G#","A#"), array("B#","C##","D##","E#","F##","G##","A##","B#","C##","D##","E#","F##","G##","A##"), array("Cb","Db","Eb","Fb","Gb","Ab","Bb","Cb","Db","Eb","Fb","Gb","Ab","Bb") ); $bass is a string, like the one inside the arrays. The $selected_scale is just a number. What I'm trying to do is to find the $bass in one of those array in the position of $selected_scale. Basically, $bass = $major_scales[$selected_scale]. Therefore I want to create a loop in order to get the elements after that. But I don't know how to manage in this case the situation. I've looked everything in internet and try various solutions without success. I'd like to know how can I do it. Thanks
Try to use next loop: // if value exists in mentioned index if (in_array($bass,$major_scales[$selected_scale])){ // index of that value in that array $tmp_ind = array_search($bass,$major_scales[$selected_scale]); // length of the array $len = count($major_scales[$selected_scale]); // store values after this value $res = []; for ($i=$tmp_ind;$i<$len;$i++){ $res[$i] = $major_scales[$selected_scale][$i]; } } print_r($res); Demo1 If you need to find value by index $selected_scale in one of these arrays and also store values after this position: foreach($major_scales as $ar){ if ($ar[$selected_scale] == $bass){ // length of the array $len = count($ar); // store values after this value $res = []; for ($i=$selected_scale;$i<$len;$i++){ $res[$i] = $ar[$i]; } } } print_r($res); Demo2
PHP build json from a dynamic number of arrays
I have a dynamic number of pages in my web project. It depends on data from the database. I may have 1 page or 10 pages. I put the data selected on each page in session, and finally want to build an array. At the moment I am building JSON from 4 arrays. (In session all the keys are level + int in ascending order. If session x is missing I don't have any data on 6+ levels) $level1 = array(); $level2 = array(); $level3 = array(); $level4 = array(); if (isset($_SESSION['level1'])) { $level1 = $_SESSION['level1']; } //the same for 3 more levels in session $array = array( "first" => ($level1), "second" => ($level2), "third" => ($level3), "fourth" => ($level4) ); json_encode($array); Example of output of the json_encode($array): {"first":["1","2"],"second":["4","6","8","9"],"third":["13","14","17","18"],"fourth":["33","34","35","36"]} I tried to check how would json_encode work with array_push(), but I get an array of JSON objects instead of a single json object. $result = array(); array_push($result, ["key1" => $_SESSION["level1"]]); array_push($result, ["key2" => $_SESSION["level2"]]); array_push($result, ["key3" => $_SESSION["level3"]]); echo json_encode($result); and the output: [{"key1":["1","2"]},{"key2":["4","5","6"]},{"key3":["13","14","15"]}] I will make everything iteratively, but I want to know if it is possible to make a single JSON object instead of array of JSONs. Thanks!
You can just add the keys to the array without any need for a function. $result = array(); $result["key1"] = $_SESSION["level1"]; $result["key2"] = $_SESSION["level2"]; $result["key3"] = $_SESSION["level3"]; echo json_encode($result);
Flatten RecursiveIteratorIterator array by children
I can't seem to figure out the best way to do this. I have a RecursiveIteratorIterator. $info = new RecursiveIteratorIterator( new GroupIterator($X), # This is a class that implements RecursiveIterator RecursiveIteratorIterator::SELF_FIRST ); Note: GroupIterator is a class that handles our custom formatted data When I loop through it, I get exactly what I expect. foreach($info as $data){ echo $info->getDepth().'-'.$data."\n"; } The output is: 0-a 1-b 2-c 2-d 1-e 2-f 0-g 1-h 2-i This is correct, so far. Now, what I want is to flatten the parents and children into a single array. I want one row for each max-depth child. The output I am trying to get is: 0-a 1-b 2-c 0-a 1-b 2-d 0-a 1-e 2-f 0-g 1-h 2-i I can't figure out how to do this. Each iteration over the loop gives me another row, how can I combine the rows together that I want?
I managed to figure it out. #ComFreek pointed me in the right direction. Instead of using a counter, I used the current depth to check when I hit the lowest child, then I added the data to the final array, otherwise I added it to a temp array. $finalArray = array(); $maxDepth = 2; foreach($info as $data){ $currentDepth = $info->getDepth(); // Reset values for next parent if($currentDepth === 0){ $currentRow = array(); } // Add values for this depth $currentRow[$currentDepth] = $data; // When at lowest child, add to final array if($currentDepth === $maxDepth){ $finalArray[] = $currentRow; } }
Try adding a counter variable: // rowNr loops through 0, 1, 2 $rowNr = 0; $curData = []; $outputData = []; foreach($info as $data){ // got last element, add the temp data to the actual array // and reset temp array and counter if ($rowNr == 2) { $outputData[] = $curData; $curData = []; $rowNr == 0; } else { // save temp data $curData[] = $info->getDepth() . '-' . $data; } $rowNr++; }
Assign values to an associated array in a loop
I am having a difficult time creating an associated array and assigning a value to the key. I have two arrays (tech_pay and tech_scans) and I am doing a simple calculation using their values and I want to create a new array called tech_per_scan but I keep getting an array with the key automatically created starting at 0. $tech_per_scan = array(); foreach($tech_pay as $key=>$value) { $pay_per_scan = $tech_pay[$key]['tot_pay']/$tech_scans[$key]['scans'];//calculate the payment per scan $tech_per_scan[] = array('id'=>$key,'pay_per_scan'=>$pay_per_scan); }
This line $tech_per_scan[] = array('id'=>$key,'pay_per_scan'=>$pay_per_scan); will add an element to you array and it will start with 0 as its index, because you did not specify its key. Similar to array_push It should be $tech_per_scan[$id]
$tech_per_scan[$id] = $pay_per_scan;
you should set value for new array like this : $tech_per_scan[$key] = $pay_per_scan ; Full code is : $tech_per_scan = array(); foreach($tech_pay as $key=>$value) { $pay_per_scan = $tech_pay[$key]['tot_pay']/$tech_scans[$key]['scans'];//calculate the payment per scan $tech_per_scan[$key] = $pay_per_scan ; }
shift array without indexOfOutBounds
I have 2 array's with the same length. array $gPositionStudents and array $gPositionInternships. Each student is assigned to a different internship, That part works. Now I want the first element (index 0) of $gPositionStudent refer to the second (index 1) element of array $gPositionInternship. That implicitly means that the last element of $gPositionStudents refer to the first element of $gPositionInternship. (I included a picture of my explanation). My Code is: // Make table $header = array(); $header[] = array('data' => 'UGentID'); $header[] = array('data' => 'Internships'); // this big array will contains all rows // global variables. global $gStartPositionStudents; global $gStartPositionInternships; //var_dump($gStartPositionInternships); $rows = array(); $i = 0; foreach($gStartPositionStudents as $value) { foreach($gStartPositionInternships as $value2) { // each loop will add a row here. $row = array(); // build the row $row[] = array('data' => $value[0]['value']); //if($value[0] != 0 || $value[0] == 0) { $row[] = array('data' => $gStartPositionInternships[$i]); } $i++; // add the row to the "big row data (contains all rows) $rows[] = array('data' => $row); } $output = theme('table', $header, $rows); return $output; Now I want that I can choose how many times, we can shift. 1 shift or 2 or more shifts. What I want exists in PHP?
Something like this: //get the array keys for the interns and students... $intern_keys = array_keys($gStartPositionInternships); $student_keys = array_keys($gStartPositionStudents); //drop the last intern key off the end and pin it to the front. array_unshift($intern_keys, array_pop($intern_keys)); //create a mapping array to join the two arrays together. $student_to_intern_mapping = array(); foreach($student_keys as $key=>$value) { $student_to_intern_mapping[$value] = $intern_keys[$key]; } You'll need to modify it to suit the rest of your code, but hopefully this will demonstrate a technique you could use. Note the key line here is the one which does array_unshift() with array_pop(). The comment in the code should explain what it's doing.
I think you want to do array_slice($gPositionsStudents, 0, X) where X is the number of moves to shift. This slices of a number of array elements. Then do array_merge($gPositionsStudents, $arrayOfSlicedOfPositions); to append these to the end of the original array. Then you can do an array_combine to create one array with key=>value pairs from both arrays.