How to use array_merge_recursive with an incremental variable? - php

I created my array within a foreach loop like so ..
$final_orders[]= array($cake_type_size => array('size' => $cake_size , 'type'=>$cake_type[0]->name, 'qty' => $order_item['qty'] ));
Outside of that foreach loop I would like to use array_merge_recursive so all the keys that are the same will be merged together
This works ..
print_r(array_merge_recursive($final_orders[1],$final_orders[2],$final_orders[3]));
But I have n type of $final_orders I need some way to constantly increment and merge to lump the same keys together.

Related

Given array keys that correspond to another array, how can I merge them?

I have the following array that is supposed to only be keys:
$keys = ['mod_4_key'];
and the bigger array which contains a lot of information:
$big_array = [ 'mod_4_key' => ['old' => '', 'info' => ''], 'mod_5_key' => ..]
I would like to, based on what is inside $keys generate a new array with the information from $big_array, as such, if we are to compute the "non-difference" between the arrays, the output should be:
$final_array = [ 'mod_4_key' => ['old' => '', 'info' => '']]
I achieved this using a classic foreach but I was wondering if there was no in-built way to achieve this.
You may be better off with a simple foreach() loop, but there are probably several ways of achieving this.
This uses array_flip() on the $keys, so that you end up with another associative array, then use array_intersect_key() with the big array first.
$final_array = array_intersect_key($big_array, array_flip($keys));

PHP merge arrays if they have the same key value

I have an array of associative arrays.
$array = [
['report_date' => 'date', 'name' => 'name'],
['report_date' => 'date', 'color' => 'color']
];
I want to sort through this array and if
$array[x]['report_date'] === $array[y]['report_date']
then I need to perform a merge that would return in this case:
$newArray = [['report_date'=>date,'name'=>name,'color'=>color]]
Of course we would need to take into account that there may be multiple arrays that fulfill this requirement and we would have to merge them as well.
I've tried a couple of things, that resulted in mapping and foreach merges that took forever to process and in the end couldn't get it working.
Any ideas?
You can create a new array, indexed by report_date and push the values into it:
$out=[];
foreach($array as $subarray){
foreach($subarray as $key=>$val){
$out[$subarray['report_date']][$key]=$val;
}
}
var_dump($out);

PHP multiple values in one key of associative Array

I stuck with a problem: I have an array with IDs and want to assign theses IDs to a key of a associative array:
$newlinkcats = array( 'link_id' => $linkcatarray[0], $linkcatarray[1], $linkcatarray[2]);
this works fine, but I don't know how many entries in $linkcatarray. So I would like to loop or similar. But I don't know how.
no push, cause it is no array
no implode, cause it is no string
no =, cause it overrides the value before
Could anyone help?
Thanks
Jim
Why not just implode it ?
$newlinkcats = array(
'link_id' => implode(
',',
$linkcatarray
)
);
Or just do this:
// Suggested by Tularis
$newlinkcats = array(
'link_id' => $linkcatarray
);
If your $linkcatarray array is only comprised of the values you wish to assign to the link_id key, then you can simply point the key at that array:
$newlinkcats = array('link_id' => $linkcatarray);
If that array contains more values that you don't want included, then take a look at array_slice() to only grab the indexes you need:
// Grabs the first 3 values from $linkcatarray
$newlinkcats = array('link_id' => array_slice($linkcatarray, 0, 3));
If your desired indexes aren't contiguous, it may be easier to cherry-pick them and use a new array:
$newlinkcats = array('link_id' => array(
$linkcatarray[7],
$linkcatarray[13],
$linkcatarray[22],
// ...
));

How do I get index of an string array on php?

Lets say I have an multidimensional string array:
.food = array(
'vegetable' => array(
'carrot' => 'blablue',
'potato' => 'bluebla',
'cauliflower' => 'blabla'
),
'Fruit' => array(
'apple' => 'chicken65',
'orange' => 'salsafood',
'pear' => 'lokkulakka'
)
);
is it possible to access the array by using index as numbers, instead of using the name of the key?
So for accessing chicken65 , I will type echo $food[1][0]; I don't want to use numbers as key, because its a big array and its more user-friendly if I use string as key and it will let me do for-loops on advanced level.
You can do foreach loops to achieve much the same thing as a typical for-loop.
foreach ($foods as $key => $value) {
//For the first iteration, $key will equal 'vegetable' and $value will be the array
}
$food[1][0] != $food[1]['apple'], so you cannot use numeric keys in this case.
try
$new_array = array_values($food);
however, variable can't start with .. It should start with $
you may want to try the function array_values but since you are dealing with multidemsional arrays, here is a solution posted by a php programmer
http://www.php.net/manual/en/function.array-values.php#103905
but it would be easier to use foreach instead of for.
You can use array_keys() on the array. The resulting array can be traversed via a for-loop and gives you the associative key.
I will show it to you for the first dimension:
$aTest = array('lol' => 'lolval', 'rofl' => 'roflval');
$aKeys = array_keys($aTest);
$iCnt = count($aKeys);
for($i = 0; $i < $iCnt; ++$i)
{
var_dump($aTest[$aKeys[$i]]);
}
You would need to do this for two dimensions but I would not recommend this. It is actually more obstrusive and slower than most other solutions.
I don't think there is something native to go this route.
And it does seem like you are trying to stretch array use a bit.
You should go OOP on this one.
Create a FoodFamilly object and a Food object in which you can store arrays if necessary and you'll be able to write a nice user-friendly code and add indices if needed.
OOP is almost always the answer :)

Which is the more efficient way to store this ordered pair in php?

Which of the following two data structures is "better"?
array('key'=>array(1,2,3,4))
OR:
array('key',array(1,2,3,4))
i.e., is it better to store the array as the second element in a two element array, or as the single element in an array with the key, 'key'.
Assume that for my purposes, in matters of convenience, they are equivalent. I am only curious whether one uses more resources than the other.
You use whichever one is appropriate for what you're trying to store.
If the key relates to the array of values and its unique then use key/value.
Worrying about resources used in this kind of situation are micro-optimizations and an irrelevant distraction.
if that's the full size of the array, then that's fine.
However, if you actually have an array like
array(
array('key', array(...)),
array('key', array(...)),
array('key', array(...)),
etc
);
instead of
array(
'key' => array(...),
'key' => array(...),
'key' => array(...),
);
Then it's not only odd, it's very unreadable.
The beaut thing of having named key to value is this:
"I want the value of Bob"
$bob = $myArray['bob'];
instead of
foreach($myArray as $key => $value) {
if ($value[0] === 'bob') { // the first value of your 2nd type
$bob = $myArray[1]; // get the next value.
}
}
Of course, for the 2nd example you could consider end(). But compare the 2, it is obvious the first example wins!

Categories