PHP:如何访问关联数组并解决“数组到字符串转换通知”? [关闭]

EDIT: I found my mistake thanks to the comments about decoding the JSON data.

I am a total rookie in PHP and couldn't find a suitable method to access Associative array.

I have this JSON data:

[{"Id":"1"},{"Id":"2"},{"Id":"3"},{"Id":"4"},{"Id":"5"},{"Id":"6"},{"Id":"7"},{"Id":"8"}]

I need to fire another MySQLi query in my PHP code which requires 1,2,3... from above data.

Implementing various solutions on this site gives me Array to String Conversion error. Please Help.

convert json data to associative array:

<?php
$json = '[{"Id":"1"},{"Id":"2"},{"Id":"3"},{"Id":"4"},{"Id":"5"},{"Id":"6"},{"Id":"7"},{"Id":"8"}]';
$data = json_decode($json,true);
echo "<pre>";
print_r($data);
echo "<pre>";
?>

You can simply use array_column amd implode as

$json = '[{"Id":"1"},{"Id":"2"},{"Id":"3"},{"Id":"4"},{"Id":"5"},{"Id":"6"},{"Id":"7"},{"Id":"8"}]';
$data = implode(',',array_column(json_decode($json,true),'Id'));
echo $data;//1,2,3,4,5,6,7,8

Explanation:

  1. json_decode($json,true) will convert your json string into an array
  2. array_column(json_decode($json,true),'Id') will returns the values from a single column of the array, identified by the column_key i.e Id over here
  3. implode will Join array elements with a glue string i.e ,.