簡體   English   中英

將一個多維數組附加到同一鍵上的另一個多維數組

[英]append one multidimensional array to another multidimensional array on same key

我有兩個數組

$input = Array
(
    [0] => Array
        (
            [section] => 725
            [location] => New Building - 26
            [rows] => DDD
            [seats] => DDD
        )

    [1] => Array
        (
            [section] => 721
            [location] => Helipad - II
            [rows] => R1,R2
            [seats] => S1,S2
        )

    [2] => Array
        (
            [section] => 724
            [location] => NDTV Times
            [rows] => R1,R2,R3
            [seats] => S1,S2,S3
        )
);

下面是第二個數組

$extra = Array
(
    [0] => dry||Obstacles Present||yes
    [1] => wet||Not Find||no
    [2] => icy||||yes
    [3] => 
)

我需要下面的所需數組:

$output =Array
(
    [0] => Array
        (
            [section] => 725
            [location] => New Building - 26
            [rows] => DDD
            [seats] => DDD
            [conditions] => dry
            [obstacles] => Obstacles Present
            [normal_lighting] => yes
        )

    [1] => Array
        (
            [section] => 721
            [location] => Helipad - II
            [rows] => R1,R2
            [seats] => S1,S2
            [conditions] => wet
            [obstacles] => Not Find
            [normal_lighting] => no
        )

    [2] => Array
        (
            [section] => 724
            [location] => NDTV Times
            [rows] => R1,R2,R3
            [seats] => S1,S2,S3
            [conditions] => icy
            [obstacles] => 
            [normal_lighting] => yes
        )
)

我做了以下序列來獲得所需的數組:

foreach($extra as $efk=>$efv)
{
    if(!empty($efv)) {
        $arr_field_value[] = explode("||", $efv);
    }
}
$arr_key = array('conditions','obstacles','normal_lighting');
foreach($arr_field_value as $fv)
{
    $arr_extra_field[]=array_combine($arr_key,$fv);
}

foreach($input as $k=>$v)
{   
    $output[]=array_merge($v,$arr_extra_field[$k]);
}
echo "<pre>"; print_r($output);

我知道這確實是一個漫長的方法,請建議我采取任何明智的方法。

您可以看到工作演示

謝謝。

foreach($extra as $key => $val){
    if($val !== ''){
        list($conditions, $obstacles, $normal_lighting) = explode('||', $val);
        $input[$key]['conditions'] = $conditions;
        $input[$key]['obstacles'] = $obstacles;
        $input[$key]['normal_lighting'] = $normal_lighting;
    }
}

我認為您正在尋找array_merge_recursive()

foreach ($extra as $key => &$extra_elem) {
    if (!$extra_elem) {
        unset($extra[$key]);
        continue;
    }
    $extra_elem = array_combine(array(
        'conditions',
        'obstacles',
        'normal_lighting',
    ), explode('||', $extra_elem));
}
$desired = array_merge_recursive($input, $extra);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM