设置相同的键值json PHP

时间:2015-10-29 19:25:34

标签: php json

我需要在我的java类中与我的解析器json进行通信,以使用图像填充gridview。下面的php代码正在输出:

{"posts":["http://fisioterapeutacamila.com/iMoveis/img/apto01.jpg",
"http://fisioterapeutacamila.com/iMoveis/img/apto01.jpg",
"http://fisioterapeutacamila.com/iMoveis/img/apto01.jpg",
"http://fisioterapeutacamila.com/iMoveis/img/apto01.jpg",    
"http://fisioterapeutacamila.com/iMoveis/img/apto01.jpg"]}

如何写它来设置相同的键值“images”来输出?:

{"posts":[{"images":"http://fisioterapeutacamila.com/iMoveis/img/apto01.jpg", 
"images":"http://fisioterapeutacamila.com/iMoveis/img/apto01.jpg",
"images":"http://fisioterapeutacamila.com/iMoveis/img/apto01.jpg",
"images":"http://fisioterapeutacamila.com/iMoveis/img/apto01.jpg",
"images":"http://fisioterapeutacamila.com/iMoveis/img/apto01.jpg"}]}

PHP文件:

$sql = "SELECT * FROM iMoveis";
$result = mysqli_query($mysqli, $sql);

$response = array();
$images = array();

while($row = mysqli_fetch_assoc($result)){

  $images[] = $row['img1'];
  $images[] = $row['img2'];
  $images[] = $row['img3'];
  $images[] = $row['img4'];
  $images[] = $row['img5'];

}

$response['posts'] = $images;

echo json_encode($response, JSON_UNESCAPED_SLASHES);

1 个答案:

答案 0 :(得分:0)

在对象中两次使用相同的密钥无效。他们只会互相覆盖。你能做的最好就是把它作为你阵中的钥匙:

$images = array('images' => array());

while($row = mysqli_fetch_assoc($result)){

  $images['images'][] = $row['img1'];
  $images['images'][] = $row['img2'];
  $images['images'][] = $row['img3'];
  $images['images'][] = $row['img4'];
  $images['images'][] = $row['img5'];
}

将输出这样的内容(注意转义):

{
    "posts":{
        "images":[
            "http:\/\/fisioterapeutacamila.com\/iMoveis\/img\/apto01.jpg",
            "http:\/\/fisioterapeutacamila.com\/iMoveis\/img\/apto01.jpg",
            "http:\/\/fisioterapeutacamila.com\/iMoveis\/img\/apto01.jpg",
            "http:\/\/fisioterapeutacamila.com\/iMoveis\/img\/apto01.jpg"
        ]
    }
}

根据评论,一组对象:

$images = array();

while ($row = mysqli_fetch_assoc($result)) {
    $images[] = array('image' => $row['img1']);
    $images[] = array('image' => $row['img2']);
    $images[] = array('image' => $row['img3']);
    $images[] = array('image' => $row['img4']);
    $images[] = array('image' => $row['img5']);
}

产生以下输出:

{

    "posts":[
        {
            "image":"http:\/\/fisioterapeutacamila.com\/iMoveis\/img\/apto01.jpg"
        },
        {
            "image":"http:\/\/fisioterapeutacamila.com\/iMoveis\/img\/apto01.jpg"
        },
        {
            "image":"http:\/\/fisioterapeutacamila.com\/iMoveis\/img\/apto01.jpg"
        },
        {
            "image":"http:\/\/fisioterapeutacamila.com\/iMoveis\/img\/apto01.jpg"
        },
        {
            "image":"http:\/\/fisioterapeutacamila.com\/iMoveis\/img\/apto01.jpg"
        }
    ]

}