首页 > 解决方案 > 需要在数组中取数组值

问题描述

我有一个数组作为查询的结果,并且在该数组内部有一个关联数组。我需要选择有价值的产品,即我需要["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"} 
        ) 
    ) 
)

标签: phparraysgetvalue

解决方案


结果你没有得到数组。你得到 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"
}

推荐阅读