php - 需要在数组中取数组值
问题描述
我有一个数组作为查询的结果,并且在该数组内部有一个关联数组。我需要选择有价值的产品,即我需要["176","143","60"]
从这个结果中得到。请帮我得到这个。
stdClass Object (
[num_rows] => 1
[row] => Array (
[setting] => {"name":"featured","product_name":"","product":["176","143","60"],"limit":"10","width":"200","height":"200","status":"1"}
)
[rows] => Array (
[0] => Array (
[setting] => {"name":"featured","product_name":"","product":["176","143","60"],"limit":"10","width":"200",
"height":"200","status":"1"}
)
)
)
解决方案
结果你没有得到数组。你得到 stdClass 这是一个对象。您必须访问其属性。并且该属性是一个数组,其中包含一个 json 编码字符串的元素,因此您必须先对其进行解码,然后访问您感兴趣的数组键。此外,您没有指定您感兴趣的产品数据(来自行或rows 属性?可以有更多的行吗?)。
https://www.php.net/manual/en/language.types.object.php
https://www.php.net/manual/en/function.json-decode.php
<?php
$data = new stdClass();
$data->num_rows = 1;
$data->row = [
'setting' => '{"name":"featured","product_name":"","product":["176","143","60"],"limit":"10","width":"200","height":"200","status":"1"}',
];
$data->rows = [
0 => [
'setting' => '{"name":"featured","product_name":"","product":["176","143","60"],"limit":"10","width":"200","height":"200","status":"1"}'
]
];
// get product array from row
var_dump(json_decode($data->row['setting'])->product);
// get product array from first row of rows
var_dump(json_decode($data->rows[0]['setting'])->product);
// get product array from all rows
array_map(function(array $row) {
var_dump(json_decode($row['setting'])->product);
}, $data->rows);
所有 3 次转储都会导致:
array(3) {
[0]=>
string(3) "176"
[1]=>
string(3) "143"
[2]=>
string(2) "60"
}
推荐阅读
- php - PHP / REST - 如何实现基于角色的 API 访问?
- android-studio - 守护进程的替代方案
- java - 为什么这个列表
不保留第一个元素? - javascript - 如何在 macOS 上的 electronjs 中使用无框窗口获得方角?
- javascript - express中间件中的高阶函数
- angular - 未触及字段时,Angular 反应式表单返回空值
- android - 如何在拖动视图时使用旋转动画以使中心位置不断变化?解决从度到度的问题
- java - 缺少服务器 jar 文件 (MCP 9.18)
- php - 通过单选按钮或 jquery 通过表单排他性选择会议会话
- jquery - 如何使用jquery连续旋转图像