Assign values to an associated array in a loop - php
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 ;
}
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
Get values of two keys in JSON array and save them in a seperate array
My JSON Array has 3 keys, like this: $json = "[{"date":"31-07-2017","time":"15:44","amount":"0"},{"date":"30-07-2017","time":"15:44","amount":"0"},{"date":"01-08-2017","time":"22:33","amount":"40"}]" I am using the following code to extract the keys, i.e the values of amount: $jdec = (json_decode($json, false)); $jlist1 = array(); $jlist2 = array(); foreach ($jdec as $element) { $jlist[] = $jlist-> amount; $jlist2[] = $jlist-> date; } But is it possible to extract to key values at once and save it in the same array?
You could save the value in the array with the date as the key like: $jlist[$element->date] = $element->amount; as long as date doesn't repeat (or you could sum amount if it does). That would probably give you a little better structure to work with.
$jlist[$element->date] = $element->amount; as suggested by Jonathan Kuhn did the job.
Can't push all array items into a second array 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;
Replace single value in multidimensional array
I am trying to unset/remove then replace/update a single value from a post meta field, but my code for array_push() and unset() are removing all of the values from each array. Here are the two halves of the code I am currently using. First, to find and remove the old value: $ID = $_GET["post_id"]; $old = $entry["85"]; $old_meta = array(); $old_meta = get_post_meta($old,'_website',false); if(in_array($ID, $old_meta[current][items])){ unset($old_meta[current][items][$ID]); } update_post_meta($old,'_website',$old_meta); Second to append the new value to the appropriate location: $port = $entry["24"]; $new_meta = array(); $new_meta = get_post_meta($port,'_website',false); $new_meta[content][items] = array(); array_push($new_meta[content][items],$ID); update_post_meta($port,'_website',$new_meta); It works to unset and insert the correct value, but any other values that were there (for both updating or unsetting) in the meta[current][items] array are removed. Before running any functions the array looks like this: pastie.org/8112933 After I run array_push it looks like this: pastie.org/8112956 After unset it looks like this: pastie.org/8112974
in_array checks to see if an element in array has a value equal to that value, not a key. So you would need to do something like this: if(in_array($ID, $old_meta['current']['items'])){ foreach($old_meta['current']['items'] as $key => $val) { if($val == $ID) { unset($old_meta['current']['items'][$key]); } } } If you need to check for a key not a value just replace in_array() with array_key_exists() and keep your current code.
How to combine multiple arrays
First off this question in in relation to this question. My issue is that a friend of mine has upwards of around 300 or so arrays that she needs to insert into the database. I get the database part as you notice in the question I linked I have that part down. My question however arises on just how exactly I am supposed to get all the arrays and bring them together so that I could could do a foreach on the arrays and check if a value is an array, if it is then use the arrays name as the table in the INSERT query. This is my updated code : $colors['Colors_All'] = array("Black","Charcoal"); // Add unique indexes $colors['Colors_Bright_All'] = array("Silver","White"); // Add unique indexes $AllArrays = get_defined_vars(); // Get all defined vars $Arrays = array(); // Set a default array foreach ($AllArrays as $varName => $value) { // Run through all the variables set in the get_defined_vars if(is_array($value) && $varName == 'colors') { // If it is an array and if the array is colors[] then $Arrays = array_merge($Arrays, $value); // Merge those arrays into the new array } } This will now give me access to all the data.
Here you go: $colors['Colors_All'] = array("Black","Charcoal","Light_Gray","Silver","White","Gold","Bronze","Copper","Platinum","Navy","Royal_Blue","Dodger_Blue","Deep_Sky_Blue","Turquoise","Tiffany_Blue"); $colors['Colors_Bright_All'] = array("Silver","White","Gold","Royal_Blue","Dodger_Blue","Deep_Sky_Blue","Deep_Green","Forest_Green","Bright_Green","Violet"); $colors['Colors_Light_All'] = array("Light_Gray","Silver","White","Gold","Dodger_Blue","Deep_Sky_Blue","Light_Blue","Bright_Green","LightGreen","Light_Green"); // This will store the merged results of each array $colorVars = array(); // Loop through all of the defined variables foreach ($colors as $colorKey => $value) { // Add the results of this array to the main $colorVars array $colorVars = array_merge($colorVars, $value); }