来自mysql assoc的PHP数组

时间:2016-06-26 06:33:23

标签: php mysql arrays

让我的价值混乱如此混乱

首页代码

MainFragment

功能事件 这个是从mysql生成结果的函数

  

$ result = mysql_query(" SELECT * from status where status =' 2'");         return $ result;

错误结果

$user = getventList();
    $response = array();
    if(mysql_num_rows($user) > 0){
    while ($row = mysql_fetch_assoc($user)){
         $response[] = $row;
         echo json_encode($response);
    }
    } else {
         return false;
    }


enter code here

我想得到的只是最后一个数组

[  {"cPID":"123","image_event":"enjoy.jpg"} 
]

[  {"cPID":"123","image_event":"enjoy.jpg"},
   {"cPID":"1234","image_event":"enjoy.jpg"}
]

[  {"cPID":"123","image_event":"enjoy.jpg"},
   {"cPID":"1234","image_event":"enjoy.jpg"},
   {"cPID":"12345","image_event":"enjoy.jpg"}
]

[  {"cPID":"123","image_event":"enjoy.jpg"},
   {"cPID":"1234","image_event":"enjoy.jpg"},
   {"cPID":"12345","image_event":"enjoy.jpg"},
   {"cPID":"123456","image_event":"enjoy.jpg"}
]

[  {"cPID":"123","image_event":"enjoy.jpg"},
   {"cPID":"1234","image_event":"enjoy.jpg"},
   {"cPID":"12345","image_event":"enjoy.jpg"},
   {"cPID":"123456","image_event":"enjoy.jpg"},
   {"cPID":"1234567","image_event":"enjoy.jpg"}
]

1 个答案:

答案 0 :(得分:2)

json_encode移出while循环。此外,请使用mysql退出并开始使用mysqliPDO个功能。

$user = getventList();
    $response = array();
    if(mysql_num_rows($user) > 0){
    while ($row = mysql_fetch_assoc($user)){
         $response[] = $row;          
    }
    } else {
         return false;
    }
    echo json_encode($response);

现在你的输出将是预期的

[  {"cPID":"123","image_event":"enjoy.jpg"},
   {"cPID":"1234","image_event":"enjoy.jpg"},
   {"cPID":"12345","image_event":"enjoy.jpg"},
   {"cPID":"123456","image_event":"enjoy.jpg"},
   {"cPID":"1234567","image_event":"enjoy.jpg"}
]