Merging two array elements into one array element in PHP - php

I want to merge two arrays into one array as follows,
Array1:
Array
(
[0] => Array
(
[id] => 3
[sku] => KOG456
[cart_id] => 2
[name] => Young Money
[slug] => young-money
[route_id] => 47
[description] =>
This is test song
[excerpt] =>
[saleprice] => 90.00
[related_products] =>
[images] => {"1c6b0883fc94c5f644497ec488cdf8cb":{"filename":"1c6b0883fc94c5f644497ec488cdf8cb.jpg","alt":"Test","caption":"","primary":true}}
[seo_title] =>
[meta] =>
[enabled] => 1
)
)
Array2:
Array
(
[0] => Array
(
[filename] => Beethovens_Symphony_No._9_(Scherzo).wma
[title] => Young Money
[size] => 599.26
)
)
Expected array result is:
Array
(
[0] => Array
(
[id] => 3
[sku] => KOG456
[cart_id] => 2
[name] => Young Money
[slug] => young-money
[route_id] => 47
[description] =>
This is test song
[excerpt] =>
[saleprice] => 90.00
[related_products] =>
[images] => {"1c6b0883fc94c5f644497ec488cdf8cb":{"filename":"1c6b0883fc94c5f644497ec488cdf8cb.jpg","alt":"Test","caption":"","primary":true}}
[seo_title] =>
[meta] =>
[enabled] => 1
[filename] => Beethovens_Symphony_No._9_(Scherzo).wma
[title] => Young Money
[size] => 599.26
)
)
How to merge these array elements into one array element ?

foreach ($origArray as $key => &$subArray)
$subArray += $arrayToBeAdded[$key];
Where $origArray is your array which is to be merged into and $arrayToBeAdded the array you merge into.

User array_merge_recursive():
$final = array_merge_recursive($array1, $array2);

Try this little known overload of the + operator for arrays:
$result = $array1[0] + $array2[0]

Use function array_merge($array1[0], $array2[0]) . Following is the example for the same
$array1 = array(0=>array('1'=>1,'2'=>2,'3'=>3));
$array2 = array(0=>array('4'=>4,'5'=>5,'6'=>6));
$result[0] = array_merge($array1[0],$array2[0]);
echo '<pre>';
print_r($result);

Since you have unique keys, you could use something as simple as the + operator (union)...
For example:
$arr1 = [1=>'testing',2=>'stack',3=>'overflow'];
$arr2 = [4=>'something',5=>'else',6=>'here'];
$arr3 = $arr1 + $arr2;
print_r($arr3);
Results:
Array ( [1] => testing [2] => stack [3] => overflow [4] => something [5] => else [6] => here )

For this php has multiple functions. You can use $arrays = array_combine($array1, $array2);.
PHP.net - array_combine
Hope it helped!

Related

Sort array by date

My array has an array for each field (i.e date, name, etc.). How do I sort the array by date? Should I create another array? Can I use sort or unsort here. If yes, how? Here is my array:
Array
(
[date] => Array
(
[0] => 03/11/2019
[1] => 03/19/2019
[2] => 03/15/2019
[3] => 12/15/2018
)
[name] => Array
(
[0] => Lowa
[1] => Stephanie
[2] => Allan
[3] => Joffer
)
[number] => Array
(
[0] => 178989898
[1] => 111111111
[2] => 222222222
[3] => 333333333
)
[unit] => Array
(
[0] => HR
[1] => VPP
[2] =>
[3] => OAT
)
[department] => Array
(
[0] => Chemistry
[1] => IT
[2] => Lab
[3] => Contractor
)
)
At the end, my first element will be:
03/19/2019 Stephanie 111111111 VPP IT
I think your data can be better organized:
$newArr = Array
(
[0] => Array
(
[date] => 03/11/2019
[name] => Lowa
[number] => 178989898
[unit] => HR
[department] => Chemistry
)
[1] => Array
(
[date] => 03/19/2019
[name] => Stephanie
[number] => 111111111
[unit] => VPP
[department] => IT
)
[2] => Array
(
[date] => 03/15/2019
[name] => Allan
[number] => 222222222
[unit] =>
[department] => Lab
)
[3] => Array
(
[date] => 12/15/2018
[name] => Joffer
[number] => 333333333
[unit] => OAT
[department] => Contractor
)
);
Then, you can simply sort it by:
function cmp($a, $b) {
if ($a["date"] == $b["date"]) return 0;
return ($a["date"] < $b["date"]) ? -1 : 1;
}
usort($newArr, "cmp");
Please be warned that dates in the format "Month/Day/Year" ar not alphabetically sortable.
You definitively should use a Year/Month/Day format for your dates, or write a more specific cmp() function...
UPDATE: To answer OP's question in comment: just reverse $row and 'field' order:
for ($row = 0; $row < count($date); $row++) {
$newArr[$row]['date'] = $date[$row];
$newArr[$row]['name'] = $name[$row];
...
}
First save the keys of your array - then by using array_value convert to integer keys so you can use the ... operator.
Then you can use array_filter with null function to re-organize your array. Next step will be to get the keys back using array_map and array_combine.
Last step - sort by "data" with usort
Consider the following example:
$arr = ["date" => ["3", "7", "5"], "name" => ["aa", "bb", "cc"]]; // this can have a lot more sub-array inside
$keys = array_keys($arr); // extract the keys for later use
$res = array_map(null, ...array_values($arr)); // transposed the array
$res = array_map(function ($e) use ($keys) {return array_combine($keys, $e);}, $res); // return the keys to the transposed array
usort($res, function ($a, $b) {return strcmp($a['date'], $b['date']);} ); // sort all by "date"
Reference:
array-keys, array-filter, array-map, usort, array-values
Notice #MarcoS post comment regarding the comparing dates

Convert associative array values in two normal array

I have array like this
Array
(
[0] => Array
(
[id] => 1
[name] => Access Control
[editable] => 0
)
[1] => Array
(
[id] => 2
[name] => CCTV
[editable] => 0
)
[2] => Array
(
[id] => 3
[name] => Fire Alarm
[editable] => 0
)
[3] => Array
(
[id] => 4
[name] => Intrusion Alarm System
[editable] => 0
)
[4] => Array
(
[id] => 5
[name] => Home Automation
[editable] => 0
)
[5] => Array
(
[id] => 6
[name] => Security Equipments
[editable] => 0
)
[6] => Array
(
[id] => 7
[name] => Audio Video
[editable] => 0
)
)
From this i want to create two new arrays
one for store id and next is for store name.
I've tried array_values method but it will returns the same array
Simply array_column can do what you want. Let your array name is $arr.
$id = array_column($arr, "id");
$name = array_column($arr, "name");
Function array_column doesn't works on PHP < 5.5. If your PHP version is >= 5.3, you can use this approach:
$ids = array_map(function($element) {
return $element['id'];
}, $arr);
$names = array_map(function($element) {
return $element['name'];
}, $arr);

How to shorten a multi dimensional array in php

I have a array that looks like this
Array
(
[11] => Array
(
[1] => Array
(
[type] => OPT
[panel] => 1
[loop] => 1
[number] => 1
[zone] => 1
[value] => 38
)
)
[12] => Array
(
[1] => Array
(
[type] => OPT
[panel] => 1
[loop] => 2
[number] => 1
[zone] => 19
[value] => 40
)
)
)
I want to delete the first dimension so that it looks like this
Array
(
[0] => Array
(
[type] => OPT
[panel] => 1
[loop] => 1
[number] => 1
[zone] => 1
[value] => 38
)
[1] => Array
(
[type] => OPT
[panel] => 1
[loop] => 2
[number] => 1
[zone] => 19
[value] => 40
)
)
How do I do that?
Sorry but I have to put in some test or the compiler won't let me post the code.
You can simply use call_user_func_array as
$result = call_user_func_array('array_merge',$your_array);
Demo
$short = array();
foreach($long as $k=>$v) {
$short[] = $array[$k][0];
}
var_dump($short);
provided that you have only one element in 2nd level
This should work for you:
Just go through each sub array and array_merge() the arrays with your $result together, e.g.
<?php
$result = [];
foreach($arr as $v)
$result = array_merge($result, $v);
print_r($result);
?>
Demo

Merge two 2d arrays on shared value from different keys

I two arrays set out like this.
First array
Array
(
[0] => Array
(
[manufacture] => Moto
[name] => ZSX 125
[code] => ZS125-48A
[cc] => 125
[bike_type] => 3 Motorcycle
[title] => Mto ZSX 125
[about] => The ZSX
)
[1] => Array
(
[manufacture] => Moto
[name] => LSM 125
[code] => STR125YB
[cc] => 125
[bike_type] => 6 Endurancemotor
[title] => Moto
[about] => Moto
)
)
Second array
Array
(
[0] => Array
(
[id] => 183
[model] => ZS125-48A
[engine_brand] => 158FMI-B
[engine_type] => Single Cylinder
)
[1] => Array
(
[id] => 172
[model] => STR125YB
[engine_brand] => K154FMI
[engine_type] => Single Cylinder
)
)
As you can see 'code' from the first array is the same as 'model' from the second and there will always be a match.
This is the array i would like to have.
Array
(
[0] => Array
(
[id] => 183
[model] => ZS125-48A
[engine_brand] => 158FMI-B
[engine_type] => Single Cylinder
[manufacture] => Moto
[name] => ZSX 125
[code] => ZS125-48A
[cc] => 125
[bike_type] => 3 Motorcycle
[title] => Moto ZSX 125
[about] => The ZSX
)
[1] => Array
(
[id] => 172
[model] => STR125YB
[engine_brand] => K154FMI
[engine_type] => Single Cylinder
[manufacture] => Moto
[name] => LSM 125
[code] => STR125YB
[cc] => 125
[bike_type] => 6 Endurancemotor
[title] => Moto
[about] => Moto
)
)
Is this possible? i have tried array_merge and array_merge_recursive, but it only appends the second array onto the end of the first, it doesnt merge it on the keys.
Deceze's solution is perfect if the two arrays are synchronized (i.e. items with matching code and model are at the same index in both arrays). If that is not the case you will need more than one line of code.
The arrays need to have string keys in order to be merged with array_merge. In this case you want to rekey the first one based on code and the second based on model. After rekeying you can merge them with array_merge_recursive.
Rekeying is easy in PHP 5.5+:
// array_column will conveniently rekey when the second argument is null
$array1 = array_column($array1, null, 'code');
$array2 = array_column($array2, null, 'model');
A bit more complicated in earlier versions:
// array_map is a more complicated way to extract a column from an array
// and array_combine will do the rekeying
$array1 = array_combine(
array_map(function($i) { return $i['code']; }, $array1),
$array1);
$array2 = array_combine(
array_map(function($i) { return $i['model']; }, $array2),
$array2);
In both cases the final step would be the same:
$result = array_merge_recursive($array1, $array2);
Looks to me like this should do it:
$array3 = array_map('array_merge', $array1, $array2);
This feeds $array1[0] and $array2[0] to array_merge, then $array1[1] and $array2[1] etc.
And, if you prefer "simpler" code... :-)
$result = array();
foreach ($one as $a) {
foreach ($two as $b) {
if ($a->code == $b->model) {
array_push($result, array_merge($a, $b));
break;
}
}
}
print_r($result);

How to sort multiple arrays in PHP

i have wrote a script to produce an array of data but now want to display in order of score. The array outputs as follows;
[display_name] => Array
(
[0] => ACT_Web_Designs
[1] => user1_design
[2] => user2_design
)
[proffesion] => Array
(
[0] => Web Developer
[1] => web developer
[2] => Web Developer
)
[score] => Array
(
[0] => 15
[1] => 6
[2] => 15
)
[img] => Array
(
[0] => ./?0000=gif&0001=3fadb8c362ff39f3322909899ff14760&0002=prof_pic
[1] =>
[2] =>
)
so in a nutshell I am wanting it to be converted as follows;
[display_name] => Array
(
[0] => ACT_Web_Designs
[1] => user2_design
[2] => user1_design
)
[proffesion] => Array
(
[0] => Web Developer
[1] => web developer
[2] => Web Developer
)
[score] => Array
(
[0] => 15
[1] => 15
[2] => 6
)
[img] => Array
(
[0] => ./?0000=gif&0001=3fadb8c362ff39f3322909899ff14760&0002=prof_pic
[1] =>
[2] =>
)
I have been looking at asort() but cant get anything to work. any help would be much appreciated.
This is exactly where the PHP's array_multisort comes to use. It is a case where you want to sort many arrays based on the comparison happening in just one of them.
I've modified the array score to have distinct values.
<?php
$arr = array(
'display_name' => array('ACT_Web_Designs','user1_design','user2_design'),
'proffesion' => array('Web Developer','web developer','web developer'),
'score' => array(12,6,15),
'img' => array('./?0000=gif&0001=3fadb8c362ff39f3322909899ff14760&0002=prof_pic','','')
);
var_dump($arr);
array_multisort($arr['score'], SORT_ASC, SORT_NUMERIC,
$arr['display_name'],
$arr['proffesion'],
$arr['img']
);
var_dump($arr);
?>
Here goes a working demo.
How about this simpler one
$arr = array("k"=>array("A","B","C"),"l"=>array(15,6,15),"n"=>array("k","l","n"));
array_multisort($arr["k"],SORT_NUMERIC,SORT_DESC,$arr["l"],$arr["n"]);
var_dump($arr);
Doesn't it work to just rsort the score array?
rsort($data['score'], SORT_NUMERIC);
I have managed to do this, i was just after a more efficient way;
$array = array(
'display_name' => array(0 => 'ACT_Web_Designs', 1 => 'user1_design', 2 => 'user2_design' ),
'proffesion' => array( 0 => 'Web Developer', 1 => 'web developer', 2 => 'Web Developer' ),
'score' => array( 0 => 15, 1 => 6, 2 => 15 ),
'img' => array( 0 => './?0000=gif&0001=3fadb8c362ff39f3322909899ff14760&0002=prof_pic', 1 => '', 2 => '' )
);
arsort($array['score'], SORT_NUMERIC );
foreach($array['score'] as $key => $val ) {
$newarray['display_name'][] = $array['display_name'][$key];
$newarray['proffesion'][] = $array['proffesion'][$key];
$newarray['score'][] = $array['score'][$key];
$newarray['img'][] = $array['img'][$key];
}
print_r($newarray);
returns
Array
(
[display_name] => Array
(
[0] => ACT_Web_Designs
[1] => user2_design
[2] => user1_design
)
[proffesion] => Array
(
[0] => Web Developer
[1] => Web Developer
[2] => web developer
)
[score] => Array
(
[0] => 15
[1] => 15
[2] => 6
)
[img] => Array
(
[0] => ./?0000=gif&0001=3fadb8c362ff39f3322909899ff14760&0002=prof_pic
[1] =>
[2] =>
)
)
Use rsort()
<?php
$fruits = array("lemon", "orange", "banana", "apple");
rsort($fruits);
reset($fruits);
while (list($key, $val) = each($fruits)) {
echo "$key = $val\n";
}
?>
This example would display:
0 = orange
1 = lemon
2 = banana
3 = apple
The most elegant solution that I could find would not reorder the data structure but merely access it in a different fashion.
$scores = $data['score'];
arsort($scores);
$keys_ordered_by_score = array_keys($scores);
Now you can, say, grab the display_name and "proffesion" that has the highest score by the following:
$first_place = $keys_ordered_by_score[0];
echo $data['display_name'][$first_place],
' is a ', $data['proffesion'][$first_place];
Of course, if you really need to reorder the data structure, this idea is useless to you. Any of the other answers using array_multisort() will likely suit that need.
This will not re-sort them for you, but it will let you go through them in the order you want. You can reassign them if you want, but I'd just use this for the output order.
Edit: This will not work, due to the possibility of non-unique key values. See Comments below, and learn from my mistake
$sort_order = $array['score'];
arsort($sort_order);
$sort_order = array_flip($sort_order);
foreach($sort_order as $key){
echo $array['display_name'][$key].' - '.$array['score'][$key];
}

Categories