php - 从 print json_encode 添加逗号

标签 php arrays json

如何在 json 打印中添加逗号?

$result = curl($url);
$result = json_decode($result , true);

$resultdata = $result ['data'];
foreach($resultdata as $data){
$print= array(
"id" => $data['id'],
"username" => $data['username'],
"text" => $data['text']
);
print json_encode($print);                              
}

这是我的代码的响应

{
    "id": "17996292388215089",
    "username": "hanikfadhilah",
    "text": "Loh kapan ini huuu pengen"
}
{
    "id": "17877856039348099",
    "username": "titan_kdk",
    "text": "Mntb" 
}
{
    "id": "17860767967398064",
    "username": "explorecentraljava",
    "text": "Terbaik fotonya lur" 
}

我想为每个 json 结果添加一个逗号

{
    "id": "17996292388215089",
    "username": "hanikfadhilah",
    "text": "Loh kapan ini huuu pengen"
},{
    "id": "17877856039348099",
    "username": "titan_kdk",
    "text": "Mntb"
},{
    "id": "17860767967398064",
    "username": "explorecentraljava",
    "text": "Terbaik fotonya lur"
}

最佳答案

您实际上需要做的是生成一个结果数组,您可以通过将值插入循环中的数组中来完成,然后在循环后对数组进行 json_encode:

$print = array();
foreach($resultdata as $data){
    $print[]= array(
        "id" => $data['id'],
        "username" => $data['username'],
        "text" => $data['text']
    );
}
print json_encode($print); 

关于php - 从 print json_encode 添加逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56318322/

相关文章:

javascript 数组到 php 文件

c++ - 使用数组索引计算位置

多线程环境下的 ruby​​ 原子操作

json - 如何使用 jq 对任意 JSON 进行完全排序?

php - PDOStatement->在生产服务器上执行比在开发服务器上慢 14 倍

javascript - 单击警告框中的是按钮时需要使用所选选项保存页面

java - volatile 数组 - 元素的内存可见性

c# - 反序列化到 List<string> 字段时出现 "Unexpected character encountered while parsing value: [."异常

c# - 不想 JSON 序列化整个类列表

php - 下一步我应该做什么?