访问这个数组数据

access to this array data

我有这个数组结果 print_r:

Array
(
    [0] => stdClass Object
        (
            [id] => 
            [place_id] => ChIJ7w0gwihoXz4R4F5KVQWLoH0
            [label] => Address Downtown - Sheikh Mohammed bin Rashid Boulevard - Dubai - United Arab Emirates
            [value] => Address Downtown - Sheikh Mohammed bin Rashid Boulevard - Dubai - United Arab Emirates
            [details] => stdClass Object
                (

但我需要得到 place_id 属性,我怎样才能得到这个?

我正在尝试使用 data[0]->place_id 数据 ["place_id"] 但总是返回我 local.ERROR: Illegal string offset 'place_id'

更新

if($select == "address"){
                    $aux = $google->getGoogleAddress($select);

                    print_r(json_decode($aux[0]->place_id));
                    /*$this->newData["place_id"] = $aux["place_id"];
                    $google->generateURL($this->newData);*/

解决方案

json_decode($aux)[0]->place_id

感谢帮助

place_id 键可能存在问题 - 它被视为字符数组(这会导致键访问错误)。

为了解决这个问题 - 您需要尝试以下解决方法之一将结果转换为数组:

  1. 如果此 stdClass 是通过 PDO 从数据库中检索的 - 将结果作为数组而不是对象获取:
$result = $sth->fetchAll(\PDO::FETCH_ASSOC);
  1. 如果它是从文件等其他地方检索到的 - 强制将结果转换为数组:
$result = (array) $results;

错误在于误解了解码的工作原理。你在做什么:

json_decode($aux[0]->place_id)

失败,因为 $aux 是一个字符串。这意味着当它 仍然是一个字符串 .

时,您正在尝试对其进行数组和对象 属性 访问

为了接收数组,JSON字符串需要先完全解码:

$decoded = json_decode($aux);

之后,$decoded 是一个包含 stdClass 个对象的数组,$decoded[0]->place_id 应该包含您需要的内容。但是,您可以一步完成(如果您不必使用数据的任何其他部分):

json_decode($aux)[0]->place_id