【问题标题】:need to take the array value inside an array需要在数组中取数组值
【发布时间】:2020-07-18 08:30:57
【问题描述】:

我有一个数组作为查询的结果,并且该数组内部有一个关联数组。我需要选择有价值的产品,即我需要从这个结果中得到["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,根据你获取SQL资源的方法,强制它返回一个关联数组,然后你就可以通过索引来获取它了。
  • 顺便说一句,重新格式化您的示例以使其更具可读性。
  • setting 不像 JSON - 所以请阅读 stackoverflow.com/questions/29308898/…

标签: php arrays getvalue


【解决方案1】:

结果你没有得到数组。你得到 stdClass 这是一个对象。 您必须访问其属性。该属性是一个数组,其中包含一个元素,该元素是一个 json 编码的字符串,因此您必须先对其进行解码,然后再访问您感兴趣的数组键。 此外,您没有指定您感兴趣的产品数据(来自 row 或 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"
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-24
    • 2016-03-12
    • 1970-01-01
    • 1970-01-01
    • 2013-11-15
    • 1970-01-01
    相关资源
    最近更新 更多