当前位置:Gxlcms > PHP教程 > 二维数组只选择目标字段

二维数组只选择目标字段

时间:2021-07-01 10:21:17 帮助过:10人阅读

我现在二维数组中有1千多条数据,每条数据中字段都有冗余,我现在每条数据中只需要我红框框出来的3条目标字段就好啦,其他的都不要,
我现在知道要用双重的foreach循环来做,但是一直做不出来,还请大家帮忙解答一下,谢谢
图如下:

回复内容:

我现在二维数组中有1千多条数据,每条数据中字段都有冗余,我现在每条数据中只需要我红框框出来的3条目标字段就好啦,其他的都不要,
我现在知道要用双重的foreach循环来做,但是一直做不出来,还请大家帮忙解答一下,谢谢
图如下:

题主你是想把二位数组里你想要的字段取出来吗, 不用两次foreach

 mt_rand(1, 2000),
        'good_name' => 'goodname' . $i,
        'xxxxxxx' => 'xxxxx',
        'wadadad' => 'adwawdadwad',
        'remake' => ''
    ];
}
//---构造测试数据 ---



$data = [];

foreach ($arry as $key => $value) {
    $data[] = [
        'platform_good_id' => $value['platform_good_id'],
        'good_name'        => $value['good_name'],
        'remake'           => $value['remake'],
    ];
}


var_dump($data);

如下:





array("a"=>"a","b"=>"b","c"=>"c","d"=>"d","e"=>"e"),
    "b"=>array("a"=>"a","b"=>"b","c"=>"c","d"=>"d","e"=>"e"),
    "c"=>array("a"=>"a","b"=>"b","c"=>"c","d"=>"d","e"=>"e"),
    "d"=>array("a"=>"a","b"=>"b","c"=>"c","d"=>"d","e"=>"e"),
    "e"=>array("a"=>"a","b"=>"b","c"=>"c","d"=>"d","e"=>"e"));

$result = array();

foreach ($arr as $k => $v){
    $result[$k] = array();
    foreach($v as $key => $value){
        if($key === "b" || $key === "d" || $key === "e"){
            $result[$k][$key] = $value;
        }
    }
}
print_r($arr);
print("
"); print_r($result); ?>

以上代码是提取其中键值为 b d e的元素然后组成一个新的数组。

人气教程排行