Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of two types

Tags:

arrays

merge

php

I have two arrays :

Array
(
    [0] => Mon
    [1] => Sun
)

Array
(
    [0] => Array
        (
            [date] => 2010-12-20
            [hours] => 4
        )

    [1] => Array
        (
            [date] => 2010-12-19
            [hours] => 2.0
        )

)

How to combine both as:

Array
(
    [0] => Array
        (
            [date] => 2010-12-20
            [hours] => 4
     [day] => Mon
        )

    [1] => Array
        (
            [date] => 2010-12-19
            [hours] => 2.0
     [day] => Sun
        )

)

Thanks - Haan

like image 436
hjaffer2001 Avatar asked Jan 02 '26 07:01

hjaffer2001


2 Answers

// copy array 2 into the result array.
$combined = $arr2;

// add a new key 'day' with value from first array.
for($i=0;$i<count($combined);$i++) {
        $combined[$i]['day'] = $arr1[$i];
}

See it

like image 133
codaddict Avatar answered Jan 03 '26 22:01

codaddict


updated.

$secondArray[0]['day'] = $firstArray[0]; 
$secondArray[1]['day'] = $firstArray[1]; 

if you are sure thay they are both the same size:

for($i = 0; $i < count($firstArray); $i++)
{
    $secondArray[$i]['day'] = $firstArray[$i]; 
}
like image 39
The Scrum Meister Avatar answered Jan 03 '26 21:01

The Scrum Meister



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!