Home >Backend Development >PHP Tutorial >Two-dimensional array selects only target fields
I now have more than 1,000 pieces of data in the two-dimensional array, and the fields in each piece of data are redundant. Now I only need the 3 target fields in the red box in each piece of data, and the others are fine. No,
I now know that I need to use a double foreach loop to do it, but I haven’t been able to do it. Please help me with the answer, thank you
The picture is as follows:
I now have more than 1,000 pieces of data in the two-dimensional array, and the fields in each piece of data are redundant. Now I only need the 3 target fields in the red box in each piece of data, and the others are fine. No,
I now know that I need to use a double foreach loop to do it, but I haven’t been able to do it. Please help me with the answer, thank you
The picture is as follows:
Questioner, do you want to extract the field you want from the two-digit array? You don’t need to do it twiceforeach
ah
<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>
As follows:
<code><!DOCTYPE html> <html> <body> <?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); ?> </body> </html></code>
The above code extracts the elements whose key value is b d e
and then forms a new array.