PHP:如何修复非法字符串偏移?

Mad*_*Pea 1 php json

我正在尝试使用json_decode函数来获取数据。

结果如下print_r

Array
(
    [ticker] => Array
        (
            [base] => BTC
            [target] => USD
            [price] => 3796.85831297
            [volume] => 173261.82951203
            [change] => 6.29130608
        )

    [timestamp] => 1545745501
    [success] => 1
    [error] => 
)
Run Code Online (Sandbox Code Playgroud)

当我想用 调用价格值时foreach,它会显示该值,但出现以下错误:

警告:非法字符串偏移“价格”

foreach ($json as $key => $value) {
       $price = $value['price'];
       echo '<br>' . $price;
}
Run Code Online (Sandbox Code Playgroud)

结果如下var_dump

array(4) {
  ["ticker"]=>
  array(5) {
    ["base"]=>
    string(3) "BTC"
    ["target"]=>
    string(3) "USD"
    ["price"]=>
    string(13) "3796.85831297"
    ["volume"]=>
    string(15) "173261.82951203"
    ["change"]=>
    string(10) "6.29130608"
  }
  ["timestamp"]=>
  int(1545745501)
  ["success"]=>
  bool(true)
  ["error"]=>
  string(0) ""
}
Run Code Online (Sandbox Code Playgroud)

有些人认为我的问题可能与这个问题重复。然而echo $json['price'];什么也没显示!

Alw*_*nny 5

你的方法没问题,但你必须确保你的$value是一个数组并且它包含price密钥,否则你会得到

警告:非法字符串偏移“价格”

要解决这个问题,您可以在 $value 和is_array()$ value [ 'price']上使用isset()!empty()

foreach ($json as $key => $value) {
      if(is_array($value) && isset($value['price']) && !empty($value['price'])){
        $price = $value['price'];
        echo '<br>' . $price;
      }
}
Run Code Online (Sandbox Code Playgroud)