. I have two array
First One
Array
(
[0] => Array
(
[date] => 2012-01-10
[result] => 65
[name] => Les océans
)
[1] => Array
(
[date] => 2012-01-11
[result] => 75
[name] => Les mers
)
[2] => Array
(
[date] => 2012-01-13
[result] => 66
[name] => Les continents
[type] => Scores
)
)
The second
Array
(
[0] => Array
(
[date_end] => 2012-01-12
[result] => 60
[name] => Step#1
[type] => Summary
)
)
And I want this for my final result
Array
(
[0] => Array
(
[date] => 2012-01-10
[result] => 65
[name] => Les océans
)
[1] => Array
(
[date] => 2012-01-11
[result] => 75
[name] => Les mers
)
[2] => Array
(
[date_end] => 2012-01-12
[result] => 60
[name] => Step#1
[type] => Summary
)
[3] => Array
(
[date] => 2012-01-13
[result] => 66
[name] => Les continents
[type] => Scores
)
)
So .... I need to combine my first array with the second and I want to order this new array by date !... Can someone can help me on hint me for doing this ? Thx !
The concat() method concatenates (joins) two or more arrays. The concat() method returns a new array, containing the joined arrays. The concat() method does not change the existing arrays.
In order to combine (concatenate) two arrays, we find its length stored in aLen and bLen respectively. Then, we create a new integer array result with length aLen + bLen . Now, in order to combine both, we copy each element in both arrays to result by using arraycopy() function.
To merge elements from one array to another, we must first iterate(loop) through all the array elements. In the loop, we will retrieve each element from an array and insert(using the array push() method) to another array. Now, we can call the merge() function and pass two arrays as the arguments for merging.
array_merge and usort is your friend.
function cmp($a, $b){
$ad = strtotime($a['date']);
$bd = strtotime($b['date']);
return ($ad-$bd);
}
$arr = array_merge($array1, $array2);
usort($arr, 'cmp');
Use array_merge() to combine the arrays, and then use sort to sort() to sort them, very simple. Would you like an example?
This should sort it for you:
function dateSort($a,$b){
$dateA = strtotime($a['date']);
$dateB = strtotime($b['date']);
return ($dateA-$dateB);
}
$arrayOne = array(
array(
'date' => '2012-01-10',
'result ' => 65,
'name' => 'Les océans'
),
array(
'date' => '2012-01-11',
'result ' => 75,
'name' => 'Les mers'
),
array(
'date' => '2012-01-13',
'result ' => 66,
'name' => 'Les continents',
'type' => 'Scores'
)
);
$arrayTwo = array(
array(
'date' => '2012-01-12',
'result ' => 60,
'name' => 'Step#1',
'type' => 'Summary'
)
);
// Merge the arrays
$combinedArray = array_merge($arrayOne,$arrayTwo);
// Sort the array using the call back function
usort($combinedArray, 'dateSort');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With