-1

我正在尝试使用 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"}} 
4

2 回答 2

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'];

[]另请注意,末尾不应有 a $id_array-- 仅在您要将新元素推送到数组时使用,而不是在分配数组变量本身时使用。

然后将for循环更改为:

foreach ($id_array as $alb_id) {

并摆脱$alb_id循环内的分配。

于 2013-10-05T07:49:41.400 回答
0

这与json无关。错误在第一行。您使用相同键的三倍,但数组键是唯一的。

array("alb_id"=>"2","alb_id"=>"4","alb_id"=>"5");

一定是 :

array(2, 4, 5);
于 2013-10-05T07:47:21.787 回答