Replace values of an array with another array in php - php

So, i am trying to display a chart where the profit and payout is rendering on a chart. If there is a no profit and payout value in chart then it should show 0.
I have an array with values of profit and payout with hour. Now i want to replace that array with an existing array of 0 values.
Here is my code
$a1=array();
for($i=0,$i<=24,$i++){
$a1['hour']=$i;
$a1['payout']='0';
$a1['profit']='0';
}
$a2=array();
$a2['hour']='2';
$a2['profit']='300';
$a2['payout']='100';
print_r(array_replace($a1,$a2));
There is something wrong with this code. Can any1 tell me what i am doing wrong?

<?php
// Initial array
$a1=array();
for($i=0;$i<=24;$i++){
// Use hour as index of array, if you use $a2[] = array(), it works
// But problem is when you change hours, lets say 12-24, if will cause problem
$a1[$i] = array(
'hour'=> $i,
'payout'=> 0,
'profit'=> 0
);
}
// Array from database
$a2=array();
$a2[] = array(
'hour'=> 2,
'payout'=> 300,
'profit'=> 100
);
$a2[] = array(
'hour'=> 5,
'payout'=> 3500,
'profit'=> 1200
);
echo '<pre>';
// Loop through second array and check if it is there in first one.
foreach( $a2 as $item) {
if(isset($a1[$item['hour']])) {
// Replace the values
$a1[$item['hour']] = $item;
}
}
print_r($a1);
?>
You are using for loop in wrong way, SyntaxError
for($i=0;$i<=24;$i++){ // <= See semi colons
}

First of all your For Loop isn't correct ! you must replace the "," with ";"

You are having a syntax error in your program.
Your working program should look something like this
$a1=array();
for($i=0;$i<=24;$i++){
$a1['hour']=$i;
$a1['payout']='0';
$a1['profit']='0';
}
$a2=array();
$a2['hour']='2';
$a2['profit']='300';
$a2['payout']='100';
print_r(array_replace($a1,$a2));
Hope this helps!

Related

How can I count the number of elements each key holds in an associative array in PHP?

I am trying to update the variable $numberOfFoods in a foreach loop with the number of elements that each key holds in an associative array. Here is my code:
$foodsArray = array (
'France' => ['Souffle' , 'Baguette' , 'Fois gras'],
'England' => ['Bangers and mash' , 'Tea and biscuits'],
'America' => ['Hamburger', 'Steak and Eggs', 'Texas chili']
);
$countriesByCuisine = array();
foreach ($foodsArray as $originCountry => $countryAssocFood) {
$numberOfFoods = count(array_values($foodsArray));
for ($countryAssocFoodIndex = 0; $countryAssocFoodIndex < $numberOfFoods; $countryAssocFoodIndex++) {
$countriesByCuisine[$countryAssocFood[$countryAssocFoodIndex]] = $originCountry;
}
}
foreach (array_keys($countriesByCuisine) as $foodFromCountry) {
echo $foodFromCountry . ', From ' . $countriesByCuisine[$foodFromCountry] . '. ';
}
As it is, this code simply sets the $numberOfFoods variable to the integer 3, rather than updating the number to reflect the number of values that the current key holds. My overall goal with this code was to learn how to transform an array such that the values become keys in a new array, with those keys holding their previous keys as values. Please forgive my messy code, as I am pretty new to programming and PHP.
#Robbie Averill is right about array_flip to achieve you "overall goal" of flipping the keys and the values.
There are multiple, more efficient, ways to fix your current code, the best one probably being array_map, but I also want to provide you with why your current code is failing:
The issue is that you are counting $foodsArray for each iteration (and it's always equal to 3), instead of counting $countryAssocFood:
$numberOfFoods = count(array_values($countryAssocFood));

Undefined offset error when iterating array after removing elements from it

I receive the following error message:
Undefined offset: 1
It points to this block of code:
$nbrProgrammingsRemoved = 0;
for($i = 0; $i<count($this->products); $i++){
if((($this->products[$i])->id)==$id){
array_splice($this->products, $i, 1);
for($j = 0; $j<count($this->programming); $j++){
/*ERROR LINE*/ if((($this->programming[$j]->out_prod_id)==$id) || (($this->programming[$j]->in_prod_id)==$id)){
$nbrProgrammingsRemoved++;
array_splice($this->programming, $j, 1);
}
}
return true;
}
}
return false;
Specifically, the error points to the innermost if-statement. (The one with "||" in it).
Now, important to note is that this error does not always occur. It only ever happens after the following code has been run:
foreach ($this->programming as $key => &$prog) {
if($prog->in_prod_id == $in_prod_id){
if($prog->in_index == $in_index){
unset($this->programming[$key]);
}
}
}
The purpose of this code is to iterate through my objects in my array and remove those associated with a certain ID. This does appear to work since the output on my website is as expected. It's only when I, after doing this, attempt to execute the first code-block that my error occurs.
I've tried troubleshooting this for a while now, but without success. Any ideas? Any more information that you need me to post?
Edit: For further clarification, if needed, the 1st code block iterates through an array to remove a single element of a specified ID. The 2nd code block iterates through another array and removes several elements.
As far as I understand, you have an array with indexes comming in a sequence:
$programming = array(
0 => ...,
1 => ...,
2 => ...,
);
At some point you unset one element, so you array looks like this:
$programming = array(
0 => ...,
2 => ...,
);
And then you're using a for loop to iterate over all numbers from 0 up to N-1 (0, 1, 2, 3, 4 ... to be precise) presuming that all indexes are filled.
I think the best solution is to use a foreach loop in this case as it will care about indexes automatically and bypass deleted items.

shuffle() everything in array?

I'm using shuffle() to randomly generate items on my site like so:
shuffle($items);
$shirts = array();
foreach ($items as $key => &$row) {
$shirts[$row['Id']] = $row['shirts'];
}
The code goes further, but basically it's running a foreach and displays 12 results. However, shuffle() seems to only return the first 12 items in the array and shuffle them. The array may contain dozens of items, and I want to shuffle through the entire array. What am I doing wrong?
We need to see more code. As of right now according to the code, it should display every result (not just 12). This must mean that you're cutting the array down to 12 before you even shuffle it.
I just wrote this function to shuffle an array. It return the array shuffled so you can still keep the original array:
`function lowellshuffle($unshuff) {
$co = count($unshuff);
$m=0;
for ($i=0;$i<$co;$i++){
$p = rand(0,count($unshuff)-1);
$shuffled[$i] = $unshuff[$p];
for ($j=0;$j<count($unshuff);$j++){
if ($unshuff[$j] !== $shuffled[$i]){
$nq[$j- $m] = $unshuff[$j];
}
else {$m++;}
}
unset($unshuff);
$unshuff = $nq;
unset($nq);
$m=0;
}
return $shuffled;
}`

Problem with associative arrays

I have always sucked at complex arrays there must be something in my brain preventing me from ever understanding them. I will try to make this example really simple so we will not go off topic. I use this code to use numbers to represent each file name:
$mod_nums = array('1' => $input_zip_path . '01_mod_1.0.2.zip',
'2' => $input_zip_path . '02_mod_1.0.1.zip',
);
So when I use $mod_nums['01'] it will display the path to that file. I have an array from the script that put these $mod_nums values into an array like so:
$files_to_zip = array(
$mod_nums['1'],
$mod_nums['2']
);
That worked fine. Now I wanted to add a $_POST value so that I can enter numbers like 1,2 and other numbers that I add to the $mod_nums array later like 1,3,6,12 for example. So I used an explode for those posted values:
$explode_mods = explode(",", trim($_POST['mods']));
Now for the big question that is racking my brain and spent hours on and cannot get it to work.... I need for $files_to_zip to still be in an array and display the posted values of $mod_nums. So it would be like:
$files_to_zip = array( HAVE $_POSTED VALUES IN HERE );
I hope that makes sense. I need $files_to_zip to remain in array format, grab the file path to the zip files from the $mod_nums array, and display it all correctly so it would dynamically output:
$files_to_zip = array('01_mod_1.0.2.zip', '02_mod_1.0.1.zip');
so posted numbers will appear in an array format for the $files_to_zip variable. Make sense? In short I need an array to have dynamic values. Thanks :)
EDIT
Phew I figured it out myself from memory when I worked on something similar many years ago. This looks tough but it isn't. I had to use a foreach and assign the variable into an array like so:
$blah = array();
foreach ($explode_mods as $value)
{
$blah[] = $mod_nums[$value];
}
then I just assigned $files_to_zip to $blah:
$files_to_zip = $blah;
works perfectly :) I just forgot how to dynamically assign values into an array.
// filenames array
$mod_nums = array('1' => $input_zip_path . '01_mod_1.0.2.zip',
'2' => $input_zip_path . '02_mod_1.0.1.zip',
);
// mod_num keys
$explode_mods = explode(',', trim($_POST['mods']));
// array to hold filenames
$files_to_zip = array();
// loop over all the mod_num keys submitted via POST
foreach($explode_mods as $key){
// save the filename to the corresponding array
$files_to_zip[] = $mod_nums[$key];
}
maybe i havn't understood you right, but won't this just be a simple foreach-loop to add the entrys to $files_to_zip like this:
$explode_mods = explode(",", trim($_POST['mods']));
foreach($explode_mods as $k){
$files_to_zip[] = $mod_nums[$k];
}

php arrays creating dynamically giving incorrect values

I want to create a array with values:
3,2,1.... and I want to use array_push and a forloop.
I have written the following code is not working..
============
<?PHP
$temp0=3;
$temp1=2;
$temp2=1;
$temp3=1;
$temp4=1;
$temp5=1;
$arraytemp=array();
for($i=0;$i<4;$i++)
{
$r="temp";
$dd=$r.$i;
array_push($arraytemp,$dd);
}
echo $arraytemp[3];
?>
can you please let me know what I am missing
This is how should you assign $dd
for($i=0;$i<4;$i++)
{
$dd=${"temp".$i};
array_push($arraytemp,$dd);
}
your $dd has the name of your var as a string. you want to use this for this technique:
array_push($arraytemp,$$dd);
Pay attention to the double $$ :)
What happens here is the following: the $dd gets replaced by the string it contains. so your call
array_push($arraytemp,$dd);
will do this:
array_push($arraytemp,'temp0');
But you want this:
array_push($arraytemp,$temp0);
so you need to show you want an acutal $var with that name, so you add the $. It's just the way the syntax works, neccessairy to distinguish between a normal string and a string that's supposed to be a variable
confusing what do you want to achieve here, do you want to:
create array with value: temp0, temp1, temp2 ...
for($i=0;$i<4;$i++){
array_push($array,"temp{$i}");
}
echo $array[3];
create array with value: 0, 1, 2, 3 ..
for($i=0;$i<4;$i++){
array_push($array,$i);
}
echo $array[3];
create array with value based on your defined variable above ($temp0, $temp1 ...)
$temp0=3;
$temp1=2;
$temp2=1;
$temp3=1;
$array = array();
for($i=0;$i<4;$i++){
$val = "temp{$i}";
array_push($array,$$val);
}
echo $array[3];
Easiest way, going by what you're requesting, although you didn't specify how many numbers you wanted to add. so for loop won't work that way. you're best off with a while loop.
$foo = array();
$i = 1;
while (some end condition) {
array_push($foo, $i);
$i++;
}
print_r($foo);

Categories