需要在一个JSON中合并许多行

时间:2015-02-18 20:36:52

标签: php mysql arrays json merge

如何制作:

 {"color":[{"id":"41","name":"red"}]}
 {"color":[{"id":"19","name":"blue"}]}
 ...

这件事由php和json_encode

 {"color":[{"id":"41","name":"red"},{"id":"19","name":"blue"},...]}

数据来自数据库,我使用以下代码:

 $json = array();
 $jsonRow= array();
 while ($row = mysqli_fetch_array($getResult)) {
    $jsonRow = array(
        $row['color'] => array(
            array(
                "id" => $row['id'],
                "name" => $row['name'],
            )
        )
    );
    array_push($json,$jsonRow);
 }

3 个答案:

答案 0 :(得分:0)

这个怎么样?

$json = array();
$colors= array();

 while ($row = mysqli_fetch_array($getResult)) {

        array_push($colors,
            array(
                "id" => $row['id'],
                "name" => $row['name'],
            )
    );
    $json = array( "colors" => $colors);

}

答案 1 :(得分:0)

 $arr= array();
 $jsonRow= array();
 while ($row = mysqli_fetch_array($getResult)) {
    $jsonRow =  array(
                "id" => $row['id'],
                "name" => $row['name'],
            );
    $arr[]=$jsonRow;
 }
$json = json_encode(array('color'=>$arr));
echo $json;

答案 2 :(得分:-2)

试试这个:

 $json = array();
 $jsonRow= array();
 while ($row = mysqli_fetch_array($getResult)) {
    $jsonRow[] = array(
       "id" => $row['id'],
       "name" => $row['name'],
    );
 }
 // color can be $row['color']
 // If its constant, I am not sure if its a good idea to keep in the loop.
 $json = array("color" => $jsonRow); 
 echo json_encode($json);