PHP/Laravel中从多维嵌套数组提取T20值生成新数组遇问题
提取多维数组中的T20值
原始数组
Array ( [0] => Array ( [id] => 1 [name] => David Warner [type] => batter [country] => Aus [age] => 33 [runs] => 11100 [wickets] => 12 [catches] => 16 [format] => Array ( [0] => Array ( [Domestic] => Array ( [0] => Array ( [ODI] => 73 [Tests] => 34 [T20] => 90 ) ) ) ) ) [1] => Array ( [id] => 2 [name] => Mark Wood [type] => bowler [country] => Eng [age] => 34 [runs] => 200 [wickets] => 120 [catches] => 2 [format] => Array ( [0] => Array ( [Domestic] => Array ( [0] => Array ( [ODI] => 40 [Tests] => 49 [T20] => 12 ) ) ) ) ) )
需求
提取所有元素中的T20值,生成如下新数组:
array:2 [▼ 0 => "90" 1 => "12" ]
已尝试无效的方法
原生PHP方法
$newArr_t20 = array_column($result_3['cricketers']['player']['format']['Domestic'], "T20");
Laravel方法
use \Illuminate\Support\Arr; $newArr_t20 = Arr::pluck($result_3, 'cricketers.player.format.Domestic.T20');
可行解决方案
问题核心是原始数组的层级嵌套:format、Domestic都包含数字索引的数组层级,之前的写法没有命中正确的路径。
方案1:原生PHP循环处理
$newArr_t20 = []; foreach ($result_3 as $player) { // 按层级获取T20值,用??确保索引不存在时不会报错 $t20Value = $player['format'][0]['Domestic'][0]['T20'] ?? null; if ($t20Value !== null) { $newArr_t20[] = $t20Value; } }
方案2:Laravel的Arr::pluck(明确索引层级)
在点语法中加入数字索引,精准定位到T20字段:
use \Illuminate\Support\Arr; $newArr_t20 = Arr::pluck($result_3, 'format.0.Domestic.0.T20');
以上两种方法都能准确提取目标值,生成符合需求的数组。
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

