php - 从多维数组中提取值并存储在单独的数组中
问题描述
我需要从多维数组中提取值。然而,起点是一个 stdClass 对象。目的是使用提取的值来创建图表。该图不是这个问题的一部分。
问题:
那么下面有没有更短更直接的方法呢?请注意,这些值可以是 100,因此我不打算一一提取这些值。
// Create an stdClass.
$products = (object)[
'group' => [
['level' => "12"],
['level' => "30"],
['level' => "70"],
]
];
// Transform stdClass to array.
$products = json_decode(json_encode($products), true);
var_dump($products);
// Calc amount of subarrays.
$amount_of_subarrays = count($products['group']);
$amount_of_subarrays = $amount_of_subarrays - 1; // Adjust since objects start with [0].
// Extract data from [$products], populate new array [$array].
$array = [];
for ($i=0; $i <= $amount_of_subarrays; $i++) {
$tmp = $products['group'][$i]['level'];
array_push($array, $tmp);
}
var_dump($array);
结果(如预期):
array(3) {
[0] =>
string(2) "12"
[1] =>
string(2) "30"
[2] =>
string(2) "70"
}
解决方案
我知道的最简单的方法是使用返回的array_column函数the values from a single column in the input array
例如array_column($products['group'], 'level')
应该返回预期的结果。
推荐阅读
- openid-connect - 使用 Rest API 对 Okta OpenID 连接进行身份验证
- laravel - 未定义变量:行(查看:resources\views\admin\category\show.blade.php)
- xamarin - 我们如何从 imageToUpload.Source 接收图像文件并传递给另一个方法
- javascript - 停止在每次渲染时调用函数
- python - 按索引上的函数过滤熊猫数据帧
- javascript - 如何从threejs应用程序中导出变形网格?
- php - 如何在 Laravel 中使用 required_if 验证?
- android - 在 Android 应用程序中使用 MangoDb
- scala - 在 Scala 中将中缀转换为后缀表示法
- python-3.x - 使用 Selenium 抓取(Python)时只有第一行