This question already has answers here:
Merge row data from multiple arrays
(6 answers)
Closed 4 months ago.
This is my array:
array
0 =>
array
'id' => int 220950
'order_reference' => string '600125479'
1 =>
array
'id' => int 220985
'order_reference' => string '498638'
and this my another array
array
0 =>
array
'entity_id' => 1
'order_status' => 'test'
1 =>
array
'entity_id' => 2
'order_status' => 'test2'
and my goal is to achieve this:
array
0 =>
array
'id' => int 220950
'order_reference' => string '600125479'
'entity_id' => 1
'order_status' => 'test'
1 =>
array
'id' => int 220985
'order_reference' => string '498638'
'entity_id' => 2
'order_status' => 'test2'
with array_merge I managed to get this(NOT my desired goal) and this all I found on stackoverflow and other forums:
array
0 =>
array
'id' => int 220950
'order_reference' => string '600125479'
1 =>
array
'id' => int 220985
'order_reference' => string '498638'
array
2 =>
array
'entity_id' => 1
'order_status' => 'test'
3 =>
array
'entity_id' => 2
'order_status' => 'test2'
Any ideas or suggestions are welcomed :) thank you
Using a foreach I can add the keys values, but I am looking for a more cleanest way :)
Here's the answer to your question using array_map and array_merge_recursive.
<?php
$array1 = array(
[
"id" => 220950,
"order_reference" => "600125479"
],
[
"id" => 220985,
"order_reference" => "498638"
]
);
$array2 = array(
[
"entity_id" => 1,
"order_status" => "test"
],
[
"entity_id" => 2,
"order_status" => "test"
]
);
$results = array();
array_map(function($array1, $array2) use (&$results) {
$results[] = array_merge_recursive($array1, $array2);
}, $array1, $array2);
var_dump($results);
This will output:
array (size=2)
0 =>
array (size=4)
'id' => int 220950
'order_reference' => string '600125479' (length=9)
'entity_id' => int 1
'order_status' => string 'test' (length=4)
1 =>
array (size=4)
'id' => int 220985
'order_reference' => string '498638' (length=6)
'entity_id' => int 2
'order_status' => string 'test' (length=4)
With the caveat that your arrays don't have a joint value to compare against so you need to make sure that the keys always line up, I think a loop like this will do the trick:
for ($i = 0; $i < count($array1); $i++)
{
$new_array[] = array_merge($array1[$i], $array2[$i]);
}
Edit: You can also use array_map() but it doesn't offer any performance advantages AFAIK, and is overall less readable.
$new_array = array_map(function($a1_v, $a2_v) { return array_merge($a1_v, $a2_v); }, $a1, $a2);
Use array_merge with array_map
$array1 = array(
[
"id" => 220950,
"order_reference" => "600125479"
],
[
"id" => 220985,
"order_reference" => "498638"
]
);
$array2 = array(
[
"entity_id" => 1,
"order_status" => "test"
],
[
"entity_id" => 2,
"order_status" => "test2"
]
);
$result = array_map("array_merge",$array1,$array2);
print_r($result);
Output
Array
(
[0] => Array
(
[id] => 220950
[order_reference] => 600125479
[entity_id] => 1
[order_status] => test
)
[1] => Array
(
[id] => 220985
[order_reference] => 498638
[entity_id] => 2
[order_status] => test2
)
)
Working example
Related
This question already has answers here:
Merge arrays of associative arrays by shared column values [duplicate]
(3 answers)
Closed 5 months ago.
I have 2 array like follows:
$array1 = [
'0' => [
'no_invoice' => 'INV0001',
'product_code' => '1111111',
],
'1' => [
'no_invoice' => 'INV0001',
'product_code' => '1111112',
]
];
$array2 = [
'0' => [
'product_code' => '1111112',
'free_valie' => 839,
'count' => 1240
],
];
Is it possible to combine arrays above to be like this:
Array(
[0] => Array
(
'no_invoice' => 'INV0001',
'product_code' => '1111111',
)
[1] => Array
(
'no_invoice' => 'INV0001',
'product_code' => '1111112',
'free_valie' => 839,
'count' => 1240
)
)
So, if array have same product code, then it will join like the example above.
I have been tried with use array merge, array_merge($array1, $array2);
But the result is like this:
Array(
[0] => Array
(
'no_invoice' => 'INV0001',
'product_code' => '1111111',
)
[1] => Array
(
'no_invoice' => 'INV0001',
'product_code' => '1111112',
)
[2] => Array
(
'product_code' => '1111112',
'free_valie' => 839,
'count' => 1240
)
)
This code will do what you want. It loops over each value in $array1, using array_search to see if the entrie's product_code is also present in $array2 (by looking through the product_code column of $array2 extracted using array_column). If it is, the values are merged. Note that we use &$val in the foreach, causing the value to be passed by reference which allows it to be modified in the loop
foreach ($array1 as &$val) {
if (($k = array_search($val['product_code'], array_column($array2, 'product_code'))) !== false) {
$val = array_merge($val, $array2[$k]);
}
}
print_r($array1);
Output:
Array
(
[0] => Array
(
[no_invoice] => INV0001
[product_code] => 1111111
)
[1] => Array
(
[no_invoice] => INV0001
[product_code] => 1111112
[free_valie] => 839
[count] => 1240
)
)
Demo on 3v4l.org
Try below one.
$array1 = [
'0' => [
'no_invoice' => 'INV0001',
'product_code' => '1111111',
],
'1' => [
'no_invoice' => 'INV0001',
'product_code' => '1111112',
]
];
$array2 = [
'0' => [
'product_code' => '1111112',
'free_valie' => 839,
'count' => 1240
],
];
foreach ($array1 as $key => &$value) {
$key = array_search($value['product_code'], array_column($array2, 'product_code'));
if ($key !== false) {
$value = array_merge($value, $array2[$key]);
unset($array2[$key]);
$array2 = array_values($array2);
}
}
echo '<pre>';
print_r($array1);
exit;
I need to reorder multidimensional array by Region Name.
But my multiarray is actually indexed by REGION_ID (first key) for semplicity like:
$array = array(
1 => array( // 1 is REGION_ID
"Value" => "Val-1",
"Children" => array(
...
)
),
2 => array( // 2 is REGION_ID
"Value" => "Val-2",
"Children" => array(
...
)
),
3 => array( // 3 is REGION_ID
"Value" => "Val-3",
"Children" => array(
...
)
),
4 => array( // 4 is REGION_ID
"Value" => "Val-4",
"Children" => array(
...
)
),
...
);
foreach ( $array as $region_id => $sub_array ) {
var_dump($region_id);
}
Where my table REGION is:
ID | Name
--------------
1 | Emilia
--------------
2 | Calabria
--------------
3 | Veneto
--------------
4 | Puglia
--------------
...
I'd like, so, to reorder my $array by Name of my table:
Calabria, then, Emilia, Puglia, Veneto... so my $array has to be:
$array = array(
2 => array(
"Value" => "Val-2",
"Children" => array(
...
)
),
1 => array(
"Value" => "Val-1",
"Children" => array(
...
)
),
4 => array(
"Value" => "Val-4",
"Children" => array(
...
)
),
3 => array(
"Value" => "Val-3",
"Children" => array(
...
)
),
...
);
I don't know how to sort using my logic...
assign the correct sorted array from database to $sorting
$sorting = ...[some function to retrive a sorted array from the database in the desired order]
for example "SELECT * FROM REGION ORDER BY Name"
ERRATA:
if you can't add the "ORDER BY" to sql query, just get the values and use usort (http://php.net/manual/en/function.usort.php) function to have the $sorting array in the correct order.
so, you should have something like (eqivalent):
$sorting = [
['ID' => 2, 'Name' => 'Calabria'],
['ID' => 1, 'Name' => 'Emilia'],
['ID' => 4, 'Name' => 'Puglia'],
['ID' => 3, 'Name' => 'Veneto']
];
or var_dump($sorting)
array (size=4)
0 =>
array (size=2)
'ID' => int 2
'Name' => string 'Calabria' (length=8)
1 =>
array (size=2)
'ID' => int 1
'Name' => string 'Emilia' (length=6)
2 =>
array (size=2)
'ID' => int 4
'Name' => string 'Puglia' (length=6)
3 =>
array (size=2)
'ID' => int 3
'Name' => string 'Veneto' (length=6)
now run the following loop:
$sorted_array = [];
foreach ($sorting as $sort_element) {
$sorted_array[] = $array[$sort_element['ID']];
}
the $sorted_array will have the required sort order
array (size=4)
0 =>
array (size=2)
'Value' => string 'Val-2' (length=5)
'Children' => ...
1 =>
array (size=2)
'Value' => string 'Val-1' (length=5)
'Children' => ...
2 =>
array (size=2)
'Value' => string 'Val-4' (length=5)
'Children' => ...
3 =>
array (size=2)
'Value' => string 'Val-3' (length=5)
'Children' => ...
<?php
$array = array(
1 => array(
"Value" => "Val-1",
"Children" => array(
)
),
2 => array(
"Value" => "Val-2",
"Children" => array(
)
),
3 => array(
"Value" => "Val-3",
"Children" => array(
)
),
4 => array(
"Value" => "Val-4",
"Children" => array(
)
),
);
$region = array(1 => 'Emilia', 2 => 'Calabria', 3 => 'Veneto', 4 => 'Puglia');
asort($region);
$new_array = [];
foreach ($region as $key => $value) {
$new_array[ $key ] = $array[ $key ];
}
print_r($new_array);
You can see this working here : http://tpcg.io/K23FfH
I have an array like this:
Array (
[0] => 10060127
[1] => 10065127
[2] => 10070127
[3] => 10075127
)
I want to add an associative array based on the value in the array. e.g. find 10070127 and an an associative array to it containing various other info. Something like:
[1] => 10065127 => Time : 10:00
Date : 16/12/2014
Count : 1
How can I recognise the correct position and push these items to this array?
You can try this:
$dataArray = array(
0 => 10060127,
1 => 10065127,
2 => 10070127,
3 => 10075127
);
$toAdd = array(
1 => array(
10065127 => array("Time" => '10:00',
"Date" => '16/12/2014',
"Count" => '1'
)
),
2 => array(
10070127 => array("Time" => '17:25',
"Date" => '11/12/2014',
"Count" => '95'
)
)
);
foreach ($toAdd as $subArray) {
$toSearch = key($subArray);
$pos = array_search($toSearch, $dataArray);
if ($pos !== false) {
unset($dataArray[$pos]);
$dataArray[$toSearch] = $subArray[$toSearch];
}
}
var_dump ($dataArray);
Output will be:
array
0 => int 10060127
3 => int 10075127
10065127 =>
array
'Time' => string '10:00' (length=5)
'Date' => string '16/12/2014' (length=10)
'Count' => string '1' (length=1)
10070127 =>
array
'Time' => string '17:25' (length=5)
'Date' => string '11/12/2014' (length=10)
'Count' => string '95' (length=2)
Something like:
$id = '10070127';
$array[array_search($id, $array)] = array($id=>array(
'time'=>'10:00',
'Date'=>'16/12/2014',
'Count'=>1));
I am trying to set the values of an empty array with another array (based on rows returned from a database).
I have tried a few things like array_merge but I just end up adding to the first array.
Just curious if there is a way to do this or would I need to iterate thought each array and merge them?
The second array can have between 1 and 3 arrays in it, while the first (the "empty") array has 3 elements always.
Empty array
(
[0] => Array
(
[id] =>
[quote_id] =>
...
)
[1] => Array
(
[id] =>
[quote_id] =>
...
)
[2] => Array
(
[id] =>
[quote_id] =>
...
)
)
Array I want to copy data from
Array
(
[0] => Array
(
[id] => 1
[quote_id] => 1
...
)
[1] => Array
(
[id] => 2
[quote_id] => 1
...
)
)
What I want to achieve
Array
(
[0] => Array
(
[id] => 1
[quote_id] => 1
...
)
[1] => Array
(
[id] => 2
[quote_id] => 1
...
)
[2] => Array
(
[id] =>
[quote_id] =>
...
)
)
You can make use of the array union operatorDocs:
$combined = $rows + $empty;
The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.
You could use array_replace(), but you'll have to be very careful with the keys, see the example in the PHP manual.
You can try
$empty = array(
"0" => Array("id" => null,"quote_id" => null,"position" => null,"type" => null,"number" => null,"cost" => null,"total" => null),
"1" => Array("id" => null,"quote_id" => null,"position" => null,"type" => null,"number" => null,"cost" => null,"total" => null),
"2" => Array("id" => null,"quote_id" => null,"position" => null,"type" => null,"number" => null,"cost" => null,"total" => null))
;
$content = Array(
"0" => Array("id" => 1,"quote_id" => 1,"position" => 1,"type" => "dwdwdw","number" => 22,"cost" => 33.00,"total" => 726.00),
"1" => Array("id" => 2,"quote_id" => 1,"position" => 2,"type" => "dwdw","number" => 22,"cost" => 22.00,"total" => 484.00));
var_dump(array_merge($content,array_unique($empty)));
Output
array
0 =>
array
'id' => int 1
'quote_id' => int 1
'position' => int 1
'type' => string 'dwdwdw' (length=6)
'number' => int 22
'cost' => float 33
'total' => float 726
1 =>
array
'id' => int 2
'quote_id' => int 1
'position' => int 2
'type' => string 'dwdw' (length=4)
'number' => int 22
'cost' => float 22
'total' => float 484
2 =>
array
'id' => null
'quote_id' => null
'position' => null
'type' => null
'number' => null
'cost' => null
'total' => null
Try this,
<?php
$result=mysql_query($query);
$i=0;
while($row=mysql_fetch_assoc($result)){
$youArray[$i]['id']=$row['id'];
$youArray[$i]['quote_id']=$row['quote_id'];
//remaining values
$i++;
}
?>
I have some difficulty sorting my array. It looks like this :
[0] => Array
(
[firstname] => Jnic
[lastname] => Fortin
[points] => Array
(
[id] => 20453
[f] => 31
[r] => 7
[total] => 82
)
)
[1] => Array
(
[firstname] => Kris
[lastname] => Anders
[points] => Array
(
[id] => 20309
[f] => 0
[r] => 1
[total] => 56
)
)
[2] => Array
(
[firstname] => Em
[lastname] => Zajo
[points] => Array
(
[id] => 20339
[f] => 8
[r] => 3
[total] => 254
)
)
I would like to sort it by "total" DESC. How could I do it? If everything sort ok the array would be order [2][0][1] (254,82,56)
You probably can use the usort function for that : it sorts an array, using a callback function to compare the elements of that array :
bool usort ( array &$array , callback $cmp_function )
This function will sort an array by
its values using a user-supplied
comparison function. If the array you
wish to sort needs to be sorted by
some non-trivial criteria, you should
use this function
If your function is defined to compare per $element['points']['total'], it should do the trick.
Edit : And here is the example, using uasort, which is the same as usort, but will keep the array keys, like pointed out by ryanday :
First, let's declare the array :
$a = array(
array(
'firstname' => 'Jnic',
'lastname' => 'Fortin',
'points' => array(
'id' => 20453,
'f' => 31,
'r' => 7,
'total' => 82,
),
),
array(
'firstname' => 'Kris',
'lastname' => 'Anders',
'points' => array(
'id' => 20309,
'f' => 0,
'r' => 1,
'total' => 56,
),
),
array(
'firstname' => 'Em',
'lastname' => 'Zajo',
'points' => array(
'id' => 20339,
'f' => 8,
'r' => 3,
'total' => 254,
),
),
);
And then, the comparison function :
function my_compare($a, $b) {
if ($a['points']['total'] > $b['points']['total']) {
return -1;
} else if ($a['points']['total'] < $b['points']['total']) {
return 1;
}
return 0;
}
And, finally, we use it :
uasort($a, 'my_compare');
var_dump($a);
And get the array, sorted by total desc :
array
2 =>
array
'firstname' => string 'Em' (length=2)
'lastname' => string 'Zajo' (length=4)
'points' =>
array
'id' => int 20339
'f' => int 8
'r' => int 3
'total' => int 254
0 =>
array
'firstname' => string 'Jnic' (length=4)
'lastname' => string 'Fortin' (length=6)
'points' =>
array
'id' => int 20453
'f' => int 31
'r' => int 7
'total' => int 82
1 =>
array
'firstname' => string 'Kris' (length=4)
'lastname' => string 'Anders' (length=6)
'points' =>
array
'id' => int 20309
'f' => int 0
'r' => int 1
'total' => int 56
ryanday > Thanks for your answer !
You will want to use usort as answered by #Pascal MARTIN, but here is the full code to achieve what you want:
function total_sort($a, $b){
$a_total = $a['points']['total'];
$b_total = $b['points']['total'];
if($a_total == $b_total) return 0;
return ($a_total > $b_total) ? -1 : 1;
}
usort($array, "total_sort");
EDIT: After I posted I saw #Pascal updated his answer to include a sample. Since I wrote my sort function a little different, I am leaving it here as another reference.
usort is a robust solution that can be very flexible for complex cases. Since your data set is relatively simple i would suggest the following:
// assuming your array has been defined in $a
$sort = array();
foreach ($a as $key => $suba)
{
// this collects the values you want to sort by and associates them with the correct index
$sort[$key] = $suba['points']['total'];
}
// this sorts the collected values
sort($sort);
// this re-sorts $a according to the sorted $sort array
array_multisort($a, $sort);
not sure about performance but this is at least AS GOOD as usort if not better
I noticed you said the proper array should be ordered [2][0][1], if that index association is important to you follow Pascal's advice with the uasort() function.