开发者

Array of two types

开发者 https://www.devze.com 2023-02-01 01:34 出处:网络
I have two arrays : Array ( [0] => Mon [1] => Sun ) Array ( [0] => Array ( [date] => 2010-12-20 [hours] =开发者_Go百科> 4

I have two arrays :

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

Array
(
    [0] => Array
        (
            [date] => 2010-12-20
            [hours] =开发者_Go百科> 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


// 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


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]; 
}


I think you may want to try: $secondArray[i]['day'] = $firstArray[i];


$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 that ampersand. Without it, $v is a copy that won't alter the original. With it, it is a reference that you can change.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号