如何将数组附加到多维数组?当它经历循环时,它需要将数据添加为数组以创建多个数组。它编码为json并发送到Android手机。
相关代码:
$data = array(
"articles" => array(
array(
'id'=> "4335",
'cat'=> "Lifestyle",
'title'=> "Welcome to field and rural life",
'url'=> "http://www.fieldandrurallife.com"
),
array(
'id'=> "4336",
'cat'=> "Lifestyle",
'title'=> "Thank You",
'url'=> "www.thankyou.com"
)
)
);
while($row = mysql_fetch_array($sql))
{
$id = $row["id"];
$cat = $row["category"];
$title = $row["title"];
$url = $row["url"];
// HOW DO I ADD THIS INTO THE ARTICLES ARRAY??
// array(
// 'id'=> $id,
// 'cat'=> $cat,
// 'title'=> $title,
// 'url'=> $url
// )
}
答案 0 :(得分:2)
简单地:
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$cat = $row["category"];
$title = $row["title"];
$url = $row["url"];
$data['articles'][] = array(
'id'=> $id,
'cat'=> $cat,
'title'=> $title,
'url'=> $url
)
}
答案 1 :(得分:1)
尝试将array_push与json_encode一起使用
当你从数据库中拉出来时,如果只拉出你需要的列,那么只需将行直接推到数组上,因为它已经是一个数组。
while($row = mysql_fetch_array($sql))
{
// Add your new array to the array
array_push($data['articles'], $row);
}
// Then you can encode your array to JSON like so.
$json_version = json_encode($data);
答案 2 :(得分:0)
使用php的方法:
array_push($data["article"], $row);