Array of two types

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:

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

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

)

Thanks - Haan

+3
source share
4 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];
}

Take a look

+2
source

updated.

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

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

for($i = 0; $i < count($firstArray); $i++)
{
    $secondArray[$i]['day'] = $firstArray[$i]; 
}
+1
source

I think you can try: $ secondArray [i] ['day'] = $ firstArray [i];

0
source
$dayOfWeek = array('Mon', 'Sun');
$dateWithHours = array( array('date'=>'12-20-2010', 'hours'=>4.0), array('date'=>'12-19-2010', 'hours'=>2.0) );

foreach(&$dateWithHours as $k=$v)
{
     $v['day'] = $dayOfWeek[$k];
}

Remember the ampersand. Without it, $ v is a copy that will not change the original. With it, you can change the link.

0
source

Source: https://habr.com/ru/post/1781379/


All Articles