警告:非法字符串偏移 'id'

Warning: Illegal string offset 'id'

我有以下代码:

 $charge = \Stripe\Charge::create(array(
      'customer' => $customer->id,
      'amount'   => $amount,
      'currency' => 'cad',
            'capture' => 'false',

      'description'=>  $courseTitle

  ));


$charge_json = $charge->__toJSON();

echo $charge_json['id'];
 echo "<pre>";
 var_dump($charge_json); 
 echo "</pre>";


}

目的是抓住下面绿色的东西:

但我收到以下错误:

Warning: Illegal string offset 'id' 

我想稍后在 mysql 查询中使用该变量

据我所知,这是一个 JSON 字符串。

您需要使用json_decode将其转换为数组或对象:

$array = json_decode($charge_json, true);
$object = json_decode($charge_json);

对于数组,您可以像访问它一样访问它。

对于对象,您可以像这样访问它:$object->id

如果 Stripe 已经提供了一种将其作为对象或数组检索的方法,您应该使用它。

$charge 已经是一个对象所以你可以只获取 $charge->id

echo $charge->id

将打印费用 ID。

调用 toJSON 将其转换为字符串,因此字符串[string] 无效php。