dongzi4030 2014-09-17 03:38
浏览 38
已采纳

如何将这部分数组复制到php中的新数组?

I have this php array X.

X= array(
    'Parent' => array(
        'title' => '123',
    )
)

I have this php array Y.

Y = array(
    'Parent' => array(
        'id' => '16',
        'title' => 'T1',
    ),
    'Children' => array(
        (int) 0 => array(
            'id' => '8',
            'serial_no' => '1',
        ),
        (int) 1 => array(
            'id' => '9',
            'serial_no' => '2',
        ),
        (int) 2 => array(
            'id' => '14',
            'serial_no' => '6',
        )
    )
)

I want to copy the Children of array Y to the parent of array X to form array Z such that it looks like this;

Z= array(
        'Parent' => array(
            'title' => '123',
        )
        'Children' => array(
            (int) 0 => array(                   
                'serial_no' => '1'
            ),
            (int) 1 => array(
                'serial_no' => '2'
            ),
            (int) 2 => array(
                'serial_no' => '6'
            )
        )
    )

Please note that the id key-value pair was removed from the Children of array Y.

I wrote some code of my own.

            $Z = array();
            $i=0;
            foreach($Y as $temp) 
            {
                $Z['Children'][$i] = $temp['Children'][$i];     
                unset($Z['Children'][$i]['id'];
                $i++;
            }    
            $Z['Parent']=$temp['Parent'];

Unfortunately, there is an undefined index error. How can this be done in php? Forget about my code if there are better approaches.

  • 写回答

2条回答 默认 最新

  • duanlian1960 2014-09-17 03:48
    关注

    Actually your approach works too, but you need to iterate over sub-array:

    $Z = array();
    $i=0;
    foreach($Y['Children'] as $temp) 
    {
        $Z['Children'][$i] = $temp;     
        unset($Z['Children'][$i]['id'];
        $i++;
    }
    

    or what I may do:

    $Z = $X;
    $Z['Children'] = array();
    foreach ( $Y['Children'] as $child ) {
        $Z['Children'][] = array(
            'serial_no' => $child['serial_no'],
        );
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探