Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
133 views
in Technique[技术] by (71.8m points)

php - invalid json resulted by foreach loop

says I want to get a value of something and store in into an arr to produce json :

foreach($item as $items){
   $items = $someting->name;

$arr = array(
   'itemName'=>$items
);

    echo json_encode($arr);

};

and it resulted

{'itemName':'shoe}{'itemName':'toy}{'itemName':'ball}

it's missing the semicolon at the back..

question from:https://stackoverflow.com/questions/65867121/php-multiple-rowsets-return-json-encode

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In most cases json_encode should be called once only. Keep adding all you want to convert to JSON in a php array, then call json_encode

$json = array('items' => array());
foreach ($items as $item) {
    $json['items'][] = array(
       'itemName' => $item->name
    );
};

echo json_encode($json);

You could also call json_encode for all your $items array without doing a loop

json_encode($items)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...