Rumah >pembangunan bahagian belakang >tutorial php >二维数组只选择目标字段
我现在二维数组中有1千多条数据,每条数据中字段都有冗余,我现在每条数据中只需要我红框框出来的3条目标字段就好啦,其他的都不要,
我现在知道要用双重的foreach循环来做,但是一直做不出来,还请大家帮忙解答一下,谢谢
图如下:
我现在二维数组中有1千多条数据,每条数据中字段都有冗余,我现在每条数据中只需要我红框框出来的3条目标字段就好啦,其他的都不要,
我现在知道要用双重的foreach循环来做,但是一直做不出来,还请大家帮忙解答一下,谢谢
图如下:
题主你是想把二位数组里你想要的字段取出来吗, 不用两次foreach
啊
<code class="php"><?php //---构造测试数据 --- $arry = []; for ($i=0; $i < 1000; $i++) { $arry[] = [ 'platform_good_id' => 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); </code>
如下:
<code> <?php $arr = array( "a"=>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("<br>"); print_r($result); ?> </code>
以上代码是提取其中键值为 b d e
的元素然后组成一个新的数组。