PHP数组拼接输出报错:Array to string conversion 如何解决?
解决PHP中Array to string conversion错误的问题
嘿,我来帮你搞定这个问题!你的代码里有两个小问题导致了这个错误,咱们一步步来修正:
问题1:$output的取值方式错误
你写的$output = ['data']['first_name'];是无效的——这个写法没有关联到前面解析出来的$response数组,相当于凭空创建了一个不完整的数组结构,根本取不到想要的first_name值。正确的做法是从$response数组里逐层取值:
$output = $response['data']['first_name'];
问题2:尝试直接拼接数组和字符串
错误提示里的「Array to string conversion」,是因为你执行echo $response.$output;的时候,$response是一个关联数组(因为json_decode第二个参数传了true),PHP没办法直接把数组转换成字符串去和$output拼接,所以抛出了这个错误。
如果你只想输出first_name的值,直接echo $output;就可以了;如果需要查看整个$response数组的内容,得用专门的数组打印函数,比如print_r()或者var_dump()。
修正后的完整代码
$json = '{"data":{"id":1,"first_name":"George","last_name":"Bluth","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg"}}'; $response = json_decode($json, true); $output = $response['data']['first_name']; // 输出单个值 echo $output; // 会打印出 "George" // 如果需要查看整个数组结构 echo '<pre>'; // 让输出格式更清晰 print_r($response); echo '</pre>';
这样修改后,代码就能正常运行啦!
内容的提问来源于stack exchange,提问作者Mitrok
相关产品推荐
相关产品推荐

