我正在尝试使用json_decode来组合一些json对象..我需要根据相册ID检索数据库值。但我不能,。
谁能告诉我我犯了哪些错误?$album_ids_id = array("album_ids"=>array(2,4,5));
// $album_ids = $_REQUEST['alb_id'];
$album_ids = json_encode($album_ids_id);
$id_list_array = json_decode($album_ids,true);
$id_array = $id_list_array->album_ids;
var_dump($id_list_array);
for($i=0;$i<sizeof($id_array);$i++)
{
$alb_id = $id_array[$i]->alb_id;
$album_sel_query = "SELECT a.a_id as id,a.a_name as name,round((b.total_value/b.total_votes),1) as rating,b.total_votes,b.total_value,a.a_pic as image,c.b_name FROM _album a inner join ratings b on b.id=a.a_id INNER JOIN _band c on c.b_id=a.b_id where a.a_id='".$alb_id."' ";
$result = mysql_query($album_sel_query);
if (!$result)
die("mySQL error: ". mysql_error());
$count = mysql_num_rows($result);
if($count > 0)
{
while($data = mysql_fetch_array($result))
{
$alb_name =$data['name'];
$singer = $data['b_name'];
$rating = $data['rating'];
$rate_value = $data['total_value'];
$rate_votes = $data['total_votes'];
$alb_pic =$data['image'];
$resmsg[] = array("Album_id"=>$alb_id,"Album_name"=>$alb_name,"Album_singer"=>$singer,"Album_rating"=>$rating,"Rating_total_value"=>$rate_value,"Rating_total_votes"=>$rate_votes,"Album_image_name"=>$alb_pic);
}
$jsonarr = array("response"=>array("success"=>"Y","ALBUM_DETAILS"=>$resmsg));
}
else
{
$jsonarr = array("response"=>array("success"=>"N","ALBUM_DETAILS"=>"Data not found"));
}
}
echo json_encode($jsonarr);
因为我使用了var_dump(),输出显示
array(1) { [0]=> array(1) { ["album_ids"]=> array(1) { ["alb_id"]=> string(1) "5" } } } {"response":{"success":"N","ALBUM_DETAILS":"Data not found"}}
答案 0 :(得分:1)
首先,这是无效的:
$album_ids_id = array("album_ids"=>array("alb_id"=>"2","alb_id"=>"4","alb_id"=>"5"));
数组中的键只能有一个值,同一个数组中不能有多个alb_id
个键。它应该是:
$album_ids_id = array("album_ids"=>array(2, 4, 5));
其次,由于您将true
作为json_decode()
的第二个参数,它返回关联数组,而不是对象。所以
$id_array[] = $id_list_array->album_ids;
应该是:
$id_array = $id_list_array['album_ids'];
另请注意,[]
末尾不应该有$id_array
- 仅在您想要将新元素推送到数组时使用,而不是在您分配数组时使用变量本身。
然后将for
循环更改为:
foreach ($id_array as $alb_id) {
并摆脱循环中的$alb_id
赋值。
答案 1 :(得分:0)
这与json无关。错误在第一行。您使用相同键的三倍,但数组键是唯一的。
array("alb_id"=>"2","alb_id"=>"4","alb_id"=>"5");
必须:
array(2, 4, 5);