PHP merge two arrays where keys match - php

I'm trying to merge two arrays where the main key matches, I tried using array_merge but the key is just overwritten.
For example I have this array:
$date = '2017-08-01';
$price_arr_1 = array();
$price_arr_1[$date]['adult_1'] = 10;
$price_arr_1[$date]['child_1'] = 2;
print_r($price_arr_1);
Which outputs:
Array ( [2017-08-01] => Array ( [adult_1] => 10 [child_1] => 2 ) )
And I have this array:
$date = '2017-08-01';
$price_arr_2 = array();
$price_arr_2[$date]['adult_2'] = 10;
$price_arr_2[$date]['child_2'] = 2;
print_r($price_arr_2);
Which outputs:
Array ( [2017-08-01] => Array ( [adult_2] => 10 [child_2] => 2 ) )
When I try and merge them like this:
print_r(array_merge($price_arr_1,$price_arr_2));
It output this:
Array ( [2017-08-01] => Array ( [adult_2] => 10 [child_2] => 2 ) )
I want to output this:
Array ( [2017-08-01] => Array ( [adult_1] => 10 [adult_2] => 10 [child_1] => 2 [child_2] => 2 ) )
Appreciated any ideas as to how to achieve the above!

In this case you can use simple array_merge_recursive:
$a1 = Array ( '2017-08-01' => Array ( 'adult_1' => 10, 'child_1' => 2, ) );
$a2 = Array ( '2017-08-01' => Array ( 'adult_2' => 20, 'child_2' => 4, ) );
echo'<pre>',print_r(array_merge_recursive($a1, $a2)),'</pre>';

You should merge with respect to date ($date):
<?php
$date = '2017-08-01';
$price_arr_1 = array();
$price_arr_1[$date]['adult_1'] = 10;
$price_arr_1[$date]['child_1'] = 2;
print_r($price_arr_1);
$date = '2017-08-01';
$price_arr_2 = array();
$price_arr_2[$date]['adult_2'] = 10;
$price_arr_2[$date]['child_2'] = 2;
print_r($price_arr_2);
print_r(array_merge($price_arr_1[$date],$price_arr_2[$date]));
Here is the output:
Array
(
[2017-08-01] => Array
(
[adult_1] => 10
[child_1] => 2
)
)
Array
(
[2017-08-01] => Array
(
[adult_2] => 10
[child_2] => 2
)
)
Array
(
[adult_1] => 10
[child_1] => 2
[adult_2] => 10
[child_2] => 2
)
Working demo: https://eval.in/839408

Are you expecting something like this?
Try this code snippet here
<?php
ini_set('display_errors', 1);
$date = '2017-08-01';
$price_arr_1 = array();
$price_arr_1[$date]['adult_1'] = 10;
$price_arr_1[$date]['child_1'] = 2;
$date = '2017-08-01';
$price_arr_2 = array();
$price_arr_2[$date]['adult_2'] = 10;
$price_arr_2[$date]['child_2'] = 2;
foreach($price_arr_1 as $someDate => $data)
{
if(isset($price_arr_2[$someDate]))
{
$price_arr_1[$someDate]=array_merge($price_arr_1[$someDate],$price_arr_2[$someDate]);
}
else
{
$price_arr_1[$someDate]=$price_arr_2[$someDate];
}
}
print_r($price_arr_1);

Better than putting a bandaid on your code, I will urge you to change your approach entirely. Most simply, avoid using any array functions at all. Just build the result array as you declare each set of elements. Improve your code's performance like this:
Code: (Demo)
$date = '2017-08-01';
$prices[$date]=['adult_1'=>10,'child_1'=>2];
$prices[$date]+=['adult_2'=>10,'child_2'=>2]; // notice the + sign
ksort($prices[$date]); // optionally, you can sort the subarrays ASC by key name
var_export($prices);
Output:
array (
'2017-08-01' =>
array (
'adult_1' => 10,
'adult_2' => 10,
'child_1' => 2,
'child_2' => 2,
),
)

Related

PHP array_push with custom key

I'm trying to merge two arrays which have a custom key using array_push, but when I use array_push it removes the custom key.
For example if I just create a normal array with a custom key it works fine:
$price_arr = array();
$date = '2017-08-01';
$insert_data = array(
$date => array(
'adult_1' => '10'
)
);
print_r($insert_data);
The result is:
Array ( [2017-08-01] => Array ( [adult_1] => 10 ) )
However if I use array push it removes the custom key, for example:
$price_arr = array();
$date = '2017-08-01';
$insert_data = array(
$date => array(
'adult_1' => '10'
)
);
array_push($price_arr, $insert_data);
$insert_data = array(
$date => array(
'child_1' => '2'
)
);
array_push($price_arr, $insert_data);
print_r($price_arr);
The result is:
Array ( [0] => Array ( [2017-08-01] => Array ( [adult_1] => 10 ) ) [1] => Array ( [2017-08-01] => Array ( [child_1] => 2 ) ) )
The result I'm trying to produce is:
Array ( [2017-08-01] => Array ( [adult_1] => 1 [child_1] => 2 ) )
Any help appreciated!
why not just do
$arr['custom_key'] = 'your value';
you do are not bound to use array_push , just assign it and it is done.
$price_arr = array();
$date = '2017-08-01';
$price_arr[$date]['adult_1'] = 10;
$price_arr[$date]['child_1'] = 2;
print_r($price_arr);
You have to use array_merge instead of array_push
$price_arr = array();
$date = '2017-08-01';
$insert_data = array(
$date => array(
'adult_1' => '10'
)
);
$price_arr = array_merge($insert_data);
$insert_data = array(
$date => array(
'child_1' => '2'
)
);
$price_arr[$date] = array_merge($price_arr[$date],$insert_data[$date]);
echo "<pre>";
print_r($price_arr);

Merging 3 arrays in PHP

I have 3 arrays as below.
$array1 = Array
(
[0] => 05/01
[1] => 05/02
)
$array2 =Array
(
[0] => ED
[1] => P
)
$array3 =Array
(
[0] => Mon
[1] => Tue
)
I want to merge these 3 arrays as below $result_array. I have written a code as below. But It gave a empty array.
$result_array =Array
(
[0] => Array
(
[0] => 05/01
[1] => ED
[2] => Mon
)
[1] => Array
(
[0] => 05/02
[1] => P
[2] => Tue
)
)
Code:
for($z=0; $z<count($array1); $z++){
$all_array[$z][] = array_merge($array1[$z],$array2[$z] );
$all_array2[$z] = array_merge($all_array[$z],$array3[$z] );
}
Please help me to do this.
Simply foreach over the first array and use the index as the key to the other arrays.
foreach ( $array1 as $idx => $val ) {
$all_array[] = [ $val, $array2[$idx], $array3[$idx] ];
}
Remember this will only work if all 3 arrays are the same length, you might like to check that first
You can simply walk through the first array with a foreach loop then access the corresponding arrays and combine the results into one big array. This will only work if the arrays are the same length so it's worth checking that before to stop any errors. Something like this:
<?php
$arr1 = ['05/01', '05/02'];
$arr2 = ['ED', 'P'];
$arr3 = ['Mon', 'Tue'];
$combined = [];
if (count($arr1) != count($arr2) || count($arr1) != count($arr3))
die("Array lengths do not match!");
foreach ($arr1 as $key => $val) {
$combined[] = [$val, $arr2[$key], $arr3[$key]];
}
var_dump($combined);
You can see an eval.in of this working here - https://eval.in/833893
Create an sample array and push to each array value with respective key
$sample = array();
for($z=0; $z<count($array1); $z++){
$sample[]=array($array1[$z],$array2[$z],$array3[$z]);
}
print_r($sample);
Out put is
Array ( [0] => Array (
[0] => 05/01
[1] => ED
[2] => Mon
)
[1] => Array (
[0] => 05/02
[1] => P
[2] => Tue
)
)
this work for n of arrays and dynamic length of array
function mergeArrays(...$arrays)
{
$length = count($arrays[0]);
$result = [];
for ($i=0;$i<$length;$i++)
{
$temp = [];
foreach ($arrays as $array)
$temp[] = $array[$i];
$result[] = $temp;
}
return $result;
}
$x = mergeArrays(['05/01' , '05/02'] , ['ED' , 'P'] , ['Mon' , 'Tus']);
$y = mergeArrays(['05/01' , '05/02' , 'X'] , ['ED' , 'P' , 'Y'] , ['Mon' , 'Tus' , 'Z'] , ['A' , 'B' , 'C']);
var_dump($x);
var_dump($y);
function merge($file_name, $titles, $description)
{
$result = array();
foreach($file_name as $key=>$name )
{
$result[] = array( 'file_name' => $name, 'title' => $titles[$key],
'description' => $description[ $key ] );
}
return $result;
}
$array1 = Array
(
'05/01',
'05/02'
);
$array2 = Array
(
'ED',
'P'
);
$array3 =Array
(
'Mon',
'Tue'
);
$result_array = array();
foreach ($array1 as $key=>$val)
{
$result_array[$key] = array($array1[$key],$array2[$key],$array3[$key]);
}
echo "<PRE>"; print_r($result_array);

Recursive count elements of multidimensional array [duplicate]

This question already has answers here:
Php recursive array counting
(7 answers)
Closed 4 months ago.
I try to make recursive function to count elements on array "levels". But can't do that for two hours already. Check example array:
Array (
[0] => Array (
[0] => Array (
[0] => Array ( )
[1] => Array ( )
)
[1] => Array ( )
)
[1] => Array (
[0] => Array (
[0] => Array (
[0] => Array ( )
[1] => Array ( )
)
)
)
)
The resulting array that count elements on different levels will be:
Array ([0] => 2, [1] => 3, [2] => 3, [3] => 2)
I made function for count total array elements, but no idea how to count each "level"
function countTotalArr($arr, $lvl) {
if ($lvl != 0) $cnt = 1;
else $cnt = 0; // don't count zero level
for ($i = 0; $i < count($arr); $i++)
$cnt += countArr($arr[$i], $lvl + 1);
return $cnt;
}
$total = countTotalArr($referralsCount, 0);
Another solution using while:
// $array is your array at the beginning of iteration
$depthMap = [];
$currentDepth = 0;
while(true) {
$depthMap[$currentDepth] = count($array);
$carry = [];
foreach($array as $item) {
if(is_array($item)) {
$carry = array_merge($carry, $item);
}
}
if(count($carry) < 1) {
break;
}
$array = $carry;
$currentDepth++;
}
Try this code:
<?php
$array = Array (
0 => Array (
0 => Array (
0 => Array ( ) ,
1 => Array ( ) ,
) ,
1 => Array ( ) ,
) ,
1 => Array (
0 => Array (
0 => Array (
0 => Array ( ),
1 => Array ( ),
),
),
) ,
);
function countTotalArr($arr, $lvl)
{
$result = array();
$countOnLevel = count($arr);
$result[$lvl] = $countOnLevel;
$tempArray = array();
foreach($arr as $index => $singleArray)
{
foreach($singleArray as $singleSubArray)
if(is_array($singleSubArray))
$tempArray[] = $singleSubArray;
}
if(!empty($tempArray))
{
$levelTemp = $lvl + 1;
$result = array_merge($result, countTotalArr($tempArray, $levelTemp));
}
return $result;
}
$total = countTotalArr($array, 0);
echo '<pre>';
print_r($total);
Result of print_r($total) is:
Array
(
[0] => 2
[1] => 3
[2] => 3
[3] => 2
)

php array_combine function is not working properly?

This is my code
$pro_qty = '';
$se_pro = '';
$pro_id_nn = $this->getDataAll("SELECT session_pro_id,session_pro_qty FROM `jp_session` WHERE session_pro_id IN (".$pro_id.") AND order_status='3'");
foreach($pro_id_nn as $pro)
{
$pro_qty[] = $pro['session_pro_qty'];
$se_pro[] = $pro['session_pro_id'];
}
$proqty = array_combine($pro_qty,$se_pro);
echo '<br>';
print_r($se_pro);
echo '<br>';
print_r($pro_qty);
echo '<br>';
print_r($proqty);
OUTOUT
first array
$se_pro = Array ( [0] => 5 [1] => 1 [2] => 1 ) ;
second array
$pro_qty = Array ( [0] => 24 [1] => 24 [2] => 22 ) ;
Finally combine two array result is
$proqty = Array ( [5] => 24 [1] => 22 );
but my expecting result is
$proqty = Array ( [5] => 24 [1] => 24 [1] => 22 );
how can i get my expecting result . thanks in advance.
Your expected result is not possible, you cannot map one key (1) to two different values (24 and 22). Perhaps you should look at a different solution, such as a "jp_session" class which contains the two values, and then just store it in a list.
simple solution
foreach($pro_id_nn as $pro)
{
$pro_qty[$pro['session_pro_id']][] = $pro['session_pro_qty'];
}
Try this one
<?php
$se_pro = Array ( 0 => 5, 1 => 1, 2 => 1 ) ;
$pro_qty = Array ( 0 => 24, 1 => 24, 2 => 22 ) ;
$a=sizeof($se_pro);
for($i=0;$i<$a;$i++)
{
$b=$se_pro[$i];
$c=$pro_qty[$i];
$temp[$b]=$c;
$i++;
}
print_r($temp);
?>
But one condition '$se_pro' values not repeat and both array are same size
in array_combine() If two keys are the same, the second one prevails..
you can get the result like -
Array
(
[24] => Array
(
[0] => 5
[1] => 1
)
[22] => 3
)
the other way can be
$keys = array ( '24', '24', '22' );
$values = array ( '5', '1', '1' );
$output = array();
$size = sizeof($keys);
for ( $i = 0; $i < $size; $i++ ) {
if ( !isset($output[$keys[$i]]) ) {
$output[$keys[$i]] = array();
}
$output[$keys[$i]][] = $values[$i];
}
this will give the output like -
Array ( [24] => Array ( [0] => 5 [1] => 1 ) [22] => Array ( [0] => 1 ) )
or you can use
<?php
$keys = array ( '24', '24', '22' );
$values = array ( '5', '1', '1' );
function foo($key, $val) {
return array($key=>$val);
}
$arrResult = array_map('foo', $keys, $values);
print_r($arrResult);
?>
depending upon which output is more suitable for you to work with.

Formatting an Array in PHP

I'm pulling an array from the database and it looks like so:
Array
(
[0] => Array
(
[tracker_id] => 28
[tracking_numbers] => hdkshwuy47937892hd
)
[1] => Array
(
[tracker_id] => 28
[tracking_numbers] => 797825464411
)
)
I need to reformat it to look like this:
Array
(
[0] => Array
(
[tracker_id] => 28
[tracking_numbers] => Array
(
[0] => hdkshwuy47937892hd
[1] => 797825464411
)
)
)
I can't seem find the right search in the array or keys to create an array of numbers for the single tracker id.
Use array_column() for < php V5.5
<?php
$a=array
( array
('tracker_id' => 28,
'tracking_numbers'=> "hdkshwuy47937892hd"
),
array('tracker_id' => 28,
'tracking_numbers' => "797825464411",
) );
$a[0]['tracking_numbers']=array_column($a,"tracking_numbers");
unset($a[1]);
print_r($a);
Demo
try this
$arr_output = array();
foreach($arr_input as $arr)
{
$tracker_id = $arr['tracker_id'];
$tracking_numbers = $arr['tracking_numbers'];
$arr_output[$traker_id][] = $tracking_numbers;
}
print_r($arr_output);
UPDATE 2:
$arr_output = array();
$arr_output1 = array();
foreach($arr_input as $arr)
{
$tracker_id = $arr['tracker_id'];
$tracking_numbers = $arr['tracking_numbers'];
$arr_output[$traker_id][] = $tracking_numbers;
}
$i=0;
foreach($arr_output as $key=>$value)
{
$arr_output1[$i]['tracker_id']=$key
$arr_output1[$i]['tracking_numbers']=$value
$i+=1;
}
print_r($arr_output1);

Categories