-1

I have an array as the result of query and inside that array has an associative array. I need to pick the value product ie i need to get ["176","143","60"] from this result. Please help me to get this.

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"} 
        ) 
    ) 
)
u_mulder
  • 54,101
  • 5
  • 48
  • 64
Vinny KB
  • 41
  • 1
  • 1
  • 7
  • it returns a stdClass, according to your approach for fetching SQL resources, force it to return an associative array and then you'll be able to fetch it by index. – biesior Jul 18 '20 at 08:34
  • 1
    BTW reformat your sample to make it more readable. – biesior Jul 18 '20 at 08:36
  • The `setting` loos like JSON - so have a read of https://stackoverflow.com/questions/29308898/how-do-i-extract-data-from-json-with-php – Nigel Ren Jul 18 '20 at 09:09

1 Answers1

0

You dont get array as a result. You get stdClass which is an object. You have to access its property. And that property is an array that contains an element that is a json encoded string, so you have to decode it first and then access array key that you are interested in. Also you didnt specify which product data you are interested in (from row or rows property? Can there be more 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);

All 3 dumps result in:

array(3) {
  [0]=>
  string(3) "176"
  [1]=>
  string(3) "143"
  [2]=>
  string(2) "60"
}
blahy
  • 1,294
  • 1
  • 8
  • 9