Add new pair key => value into array from another array - php

I have tried array_merge, to merge them based on similar keys, array_push, various [] combinations but I just can't figure this one out. I have two arrays, one looks like:
Array
(
[650] => Array
(
[Kampan] =>
[ZelvaUL] => 650
[ZelvaOV] =>
[OCS] =>
[Rezim] => Ruční
)
[651] => Array
(
[Kampan] => 3003C_DSL_upsell_TV_SU
[ZelvaUL] => 651
[ZelvaOV] =>
[OCS] => 21
[Rezim] => IN
)
[652] => Array
(
[Kampan] =>
[ZelvaUL] => 652
[ZelvaOV] =>
[OCS] => 22
[Rezim] => IN
)
And, I want to add one new key to each of 650, 651, 652... sub-arrays (I will call the key 'Barva'), and short set of values from another array (10 total) to periodically loop in each sub-array under that key, so that 1st and 11th value is the same, 2nd and 12th is the same and so on, and all to be under the same key.
It would look like:
Array
(
[650] => Array
(
[Kampan] =>
[ZelvaUL] => 650
[ZelvaOV] =>
[OCS] =>
[Rezim] => Ruční
[Barva] => 1
)
[651] => Array
(
[Kampan] => 3003C_DSL_upsell_TV_SU
[ZelvaUL] => 651
[ZelvaOV] =>
[OCS] => 21
[Rezim] => IN
[Barva] => 2
)
[652] => Array
(
[Kampan] =>
[ZelvaUL] => 652
[ZelvaOV] =>
[OCS] => 22
[Rezim] => IN
[Barva] => 3
)
...
[660] => Array
(
[Kampan] => ...
[ZelvaUL] => ...
[ZelvaOV] => ...
[OCS] => ...
[Rezim] => ...
[Barva] => 1
)
Seriously, I am out of ideas...
Thanks for any help guys.
edit:
This is the array I want to add:
$camp_barvy = array(
'background-color:#ffffff;color:#111111;',
'background-color:#ffcc02;color:#111111;',
'background-color:#ff7700;color:#ffffff;',
'background-color:#ff2323;color:#ffffff;',
'background-color:#ff00aa;color:#ffffff;',
'background-color:#aa44ff;color:#ffffff;',
'background-color:#1188ff;color:#ffffff;',
'background-color:#11ddff;color:#111111;',
'background-color:#00dd77;color:#111111;',
'background-color:#119911;color:#ffffff;'
);
I wanna do some large and extensive conditioned formatting and both javascript and php if statement make the loading too slow, so I figured I will make the format part of the array I already look in for the values based on which I choose the desired format.
Really, its the best choice :)

What you want to do is iterate over each value in your "input" array and insert in it a new value taken from your "data" array (those 10 values you mention). When your data array is exhausted, you want to loop back to its start and continue inserting values in the "input" array elements.
So you want something like:
foreach ($input as &$row) {
$row['Brava'] = $next_item_from_data_array;
}
which leaves just the problem of how to easily iterate and loop over the data array.
A convenient and modern way of doing this is by using the built-in SPL iterators: an ArrayIterator for your data array and an InfiniteIterator around that so that you loop back to the start automatically as required. This way you also don't have to assume anything about your data array (such as if it is numerically indexed or not).
For example:
$dataIterator = new InfiniteIterator(new ArrayIterator($data));
$dataIterator->rewind();
foreach ($input as &$row) {
$row['Brava'] = $dataIterator->current();
$dataIterator->next();
}
// After iterating by reference (&$row) it is always a good idea to unset
// the reference so that you don't reuse it later on by mistake -- although
// this is not required and the program will work correctly without it.
unset($row);
See it in action.

Related

get the index of multi dimension array , with value in php

I want to get the index of an array without foreach. this is sample array
Array
(
[0] => Array
(
[gcr_distance] => 31.0
[gcr_id] => 23
)
[1] => Array
(
[gcr_distance] => 28.0
[gcr_id] => 22
)
[2] => Array
(
[gcr_distance] => 26.0
[gcr_id] => 20
)
[3] => Array
(
[gcr_distance] => 110.0
[gcr_id] => 21
)
)
suppose if my data is gcr_id=21, by comparing with the above array it should give me an index of array 3
You can use a combination of array_search and array_column. array_column returns all the values which have a key of 'gcr_id' and then array_search returns the key which corresponds to a value of 21.
$array = array(
array('gcr_distance' => 31.0, 'gcr_id' => 23),
array('gcr_distance' => 28.0, 'gcr_id' => 22),
array('gcr_distance' => 26.0, 'gcr_id' => 20),
array('gcr_distance' => 110.0, 'gcr_id' => 21)
);
$key = array_search(21, array_column($array, 'gcr_id'));
echo $key;
Output:
3
Inspired by #Elementary's comment, I did some bench testing on this. What I found was that on a 100k entry array, array_search and array_column took around 80% of the time that a foreach based search took when the entry was not in the array, 95% of which was in the call to array_column. So it would seem that on average, a foreach based search would be faster.

Adding to a multidimensional associative array (in PHP)

I'm returning an associative array via PDO that has the structure:
Array
(
[0] => Array
(
[pesttopicID] => 42
[sPestName] => CMSM Trap Surveying and Pest Management
[quizID] => 609
[bTier1] => 1
[sDesc] => Workshop assessment
)
[1] => Array
(
[pesttopicID] => 34
[sPestName] => Trap Surveyor
[quizID] => 451
[bTier1] => 1
[sDesc] => Competency for CM OAP
)
)
I want to add a key-value pair to the "inner" array, but all my attempts of trying to use posted solutions to the generic issue of adding to an associative array...
:
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$newkey='myNewKey';
$newval='myNewValue';
foreach($results as $row){
$results[][$newkey] = $newval;
foreach ($row as $key=>$value){
... some reporting stuff
}
}
...result in the pair being added to the "outer" array e.g.
Array
(
[0] => Array <---- I want the new pair in this "inner" array
(
[pesttopicID] => 42
[sPestName] => CMSM Trap Surveying and Pest Management
[quizID] => 609
[bTier1] => 1
[sDesc] => Workshop assessment
)
[1] => Array <---- I want the new pair in this "inner" array
(
[pesttopicID] => 34
[sPestName] => Trap Surveyor
[quizID] => 451
[bTier1] => 1
[sDesc] => Competency for CM OAP
)
[2] => Array
(
[myNewKey] => myNewValue
)
)
Is this possible?
Thanks/Tom
You have to it like below:-
$newkey='myNewKey';
$newval='myNewValue';
foreach($results as &$row){ //use reference variable
$row[$newkey] = $newval;// remove the second foreach if not necessary
//if second foreach is necessary then add it no problem
}
Output:-https://eval.in/856983
Or you can do like this also:-
$newkey='myNewKey';
$newval='myNewValue';
foreach($results as $key=>$row){ //use key now
$results[$key][$newkey] = $newval;// remove the second foreach if not necessary
//if second foreach is necessary then add it no problem
}
Output:-https://eval.in/856987

PHP removing an array element and inserting it into another array

I have 2 arrays which are in the same form as below; for examples sake, lets call them $array1 and $array2
Array (
[Element1] => Array
(
[id] => 11
[morethings] => 145
[somemore] => namehere
)
[Element2] => Array
(
[id] => 11
[morethings] => 145
[somemore] => namehere
)
[Element3] => Array
(
[id] => 11
[morethings] => 145
[somemore] => namehere
)
)
What I need to do is take Element2 from the first array and then insert it into array2 as NewElement2
I have the following below but it keeps returning nothing at all in array2
$searchArray = array_search('Element2', $array1);
array_splice($array2, $searchArray, 1, array('NewElement2'));
Any help would be greatly appreciated.
for assign the value you can simply
$array2['Element2'] = $array1['Element2'];
(this append or repalce the entry for Elemet2 in $array2)
and for remove the value
unset($array1['Element2']);

Put a key of end of an array in php

I have this array:
Array
(
[0] => Array
(
[date] => 2016-03-08
[value] => Array
(
[key_1] => Array
(
[test_1] => 1
[test_2] => 10
[test_3] => 1000
[test_4] => 200
)
[key_2] => Array
(
[test_1] => 1
[test_2] => 15
[test_3] => 1500
[test_4] => 100
)
)
)
Now I have another array :
Array
(
[key_3] => Array
(
[test_1] =>
[test_2] =>
[test_3] =>
[test_4] => 1
)
)
I want to add this last array in the first array.
I try like this : array_push($ymlParsedData[]['value'], $a_big_gift); but not work. Can you help me please ?
You can't use $ymlParsedData[] for accessing specific element, it is a shorthand for pushing data to array.
You can use either
// NB! array_push() just adds the values, key 'key_3' is removed
array_push($ymlParsedData[0]['value'], $a_big_gift);
or
// will keep key 'key_3'
$ymlParsedData[0]['value']['key_3'] = $a_big_gift['key_3'];
or
// use array_merge() instead
$ymlParsedData[0]['value'] = array_merge($ymlParsedData[0]['value'], $a_big_gift);
A complicated answer, but this might solve your issue:
$key_name = array_keys($a_big_gift)[0];
$ymlParsedData[0]['value'][$key_name] = $a_big_gift[$key_name];
echo '<pre>'; print_r($ymlParsedData); exit;
Note: For making it dynamic and for more than one value of $a_big_gift, you need to loop it and achieve your result.
Try this
array_push($ymlParsedData[0]['value'], $a_big_gift['key_3']);

Array_Unique filtering

I have an multidimensional array:
Array
(
[0] => Array
(
[Id] => 1
[MTime_Id] => 1
[MName] => Breakfast
[DName] => Other Cereals
[IName] =>
[Date] => 2013-02-05
)
[1] => Array
(
[Id] => 1
[MTime_Id] => 1
[MName] => Breakfast
[DName] => Porridge
[IName] => Oats,Milk,Sugar
[Date] => 2013-02-06
)
[2] => Array
(
[Id] => 1
[MTime_Id] => 1
[MName] => Breakfast
[DName] => Porridge
[IName] => Oats,Milk,Sugar,Oats,Milk,Sugar
[Date] => 2013-02-05
)
)
And I am trying to use array unique to filter this
[IName] => Oats,Milk,Sugar,Oats,Milk,Sugar
I am having no luck. How can I filter the duplicates?
Cheers.
If you filter input and therefore don't have extra spaces in IName field, you can use something as simple as this for filtering:
$array[2]['IName'] = implode(',', array_unique(explode(',', $array[2]['IName'])));
The problem is that you habe in array two Oats,Milk,Sugar as element of IName, in array three you have Oats,Milk,Sugar,Oats,Milk,Sugar. This is not the same!
"Oats,Milk,Sugar"=="Oats,Milk,Sugar,Oats,Milk,Sugar" (or "Oats,Milk,Sugar".equals("Oats,Milk,Sugar,Oats,Milk,Sugar")) is false.
If you want to have it unique you have to explode the single results and then do a unique on it or you have to store the single values in seperate fields...
BTW: Here is a link how to remove duplicates from a multi dimensional array How to remove duplicate values from a multi-dimensional array in PHP
I am not sure if a function exists for that, here is a simple solution,
you can loop the array, and get the result of each value, then explode result, and insert it into an array.
then use the array_unique function.
try this:
$result = array();
foreach($arrays as $array)
{
$tmp = $array['IName'];
$tmp2 = explode(',',$tmp);
foreach ($tmp2 as $t)
{
$result[]=$t;
}
}
$array_unique = array_unique($result);

Categories