如何从PHP中的关联数组创建二维数组

时间:2019-03-25 20:20:20

标签: php laravel foreach

我需要在php中将关联数组转换为二维数组,原始数组如下所示

    array:7 [▼
  "data" => "data"
  "id_1553539135251" => "<p>nsmn</p>"
  "about" => "about"
  "id_1553539141598" => "<p>uiu</p>"

我的代码

        $data = $request->all();
        $json = array();
        foreach($data as $key => $value){

            if(strpos($key, 'id') !== false){
                $json[$key]['content'] = $value;
            }
        }

我需要以下各项的输出

array:3 [▼
  "id_1553539135251" => array:1 [▼
    "content" => "<p>nsmn</p>"
    "data" => "data"
]
  "id_1553539141598" => array:1 [▼
    "content" => "<p>uiu</p>"
    "about" => "about"
  ]
]

但是我的代码输出

array:3 [▼
  "id_1553539135251" => array:1 [▼
    "content" => "<p>nsmn</p>"
  ]
  "id_1553539138029" => array:1 [▼
    "content" => "<p>jjkjk</p>"
  ]
  "id_1553539141598" => array:1 [▼
    "content" => "<p>uiu</p>"
  ]
]

对如何实现所需输出的指导表示赞赏。

1 个答案:

答案 0 :(得分:0)

<?php
$test=array(
		array(

			"data" => "data",
		  "id_1553539135251" => "<p>nsmn</p>",
		  "about" => "about",
		  "id_1553539141598" => "<p>uiu</p>"
		),
);
$output=array();
foreach($test as $item){
	$i=0;
	$tt='';
	foreach($item as $k=>$v){
		
		if(strpos($k, 'id') !== false){
			$output[$k]=array(
					'content'=>$item[$k],
					'header'=>$tt,
		);
		}else{
			$tt=$v;	
		}
	}
}
print_r($output);