猿问

转换多维数组(php)

我目前正在努力将 PHP 中的这个数组转换为更简化的数组。这是我的数组开始存储在$array:


   [0] => Array

       (

           [name] => name-1

           [value] => xXX

       )


   [1] => Array

       (

           [name] => name-2

           [value] => YYY

       )

我想从这个数组转换到这个简化的数组$array_new:


   [0] => Array

       (

           [name-1] => xXX

       )


   [1] => Array

       (

           [name-2] => YYY

       )

我很遗憾不知道要开始...有人可以帮我吗?


编辑:通过 array_column() 或 foreach 循环转换数组后,我仍然无法使用 $array_new['name-2']; 获得正确的数据;


江户川乱折腾
浏览 278回答 3
3回答

当年话下

您可以使用array-column来做到这一点。文件说:array_column ( 数组 $input , 混合 $column_key [, 混合 $index_key = NULL ] ) : 数组这样做:$first_names = array_column($array, 'value', 'name');现场示例:3v4l

梵蒂冈之花

使用 foreach:<?php$items =[&nbsp; &nbsp; [&nbsp; &nbsp; &nbsp; &nbsp; 'plant' => 'fern',&nbsp; &nbsp; &nbsp; &nbsp; 'colour' => 'green'&nbsp; &nbsp; ],&nbsp; &nbsp; [&nbsp; &nbsp; &nbsp; &nbsp; 'plant' => 'juniper',&nbsp; &nbsp; &nbsp; &nbsp; 'colour' => 'blue'&nbsp; &nbsp; ]];foreach($items as $item) {&nbsp; &nbsp; $output[][$item['plant']]=$item['colour'];}var_dump($output);输出:array(2) {&nbsp; &nbsp; [0]=>&nbsp; &nbsp; array(1) {&nbsp; &nbsp; ["fern"]=>&nbsp; &nbsp; string(5) "green"&nbsp; &nbsp; }&nbsp; &nbsp; [1]=>&nbsp; &nbsp; array(1) {&nbsp; &nbsp; ["juniper"]=>&nbsp; &nbsp; string(4) "blue"&nbsp; &nbsp; }}

慕少森

问题好吧,这是我看到很多初学者都在处理的问题。有点创意:回答//Let's get your old array:$old = [&nbsp; &nbsp;0 => [&nbsp; &nbsp; &nbsp; 'name' => 'name-1',&nbsp; &nbsp; &nbsp; 'value' => 'xXX'&nbsp; &nbsp;],&nbsp; &nbsp;1 => [&nbsp; &nbsp; &nbsp; 'name' => 'name-2',&nbsp; &nbsp; &nbsp; 'value' => 'YYY'&nbsp; &nbsp;]];//Let's create an array where we will store the new data:$result = [];foreach($old as $new) { //Loop through&nbsp; &nbsp;$result[$new['name']] = $new['value']; //Store associatively with value as value}var_dump($result);结果:Array[2] => [&nbsp; &nbsp;[name-1] => xXX,&nbsp; &nbsp;[name-2] => YYY];
随时随地看视频慕课网APP
我要回答