dongshun1884 2016-03-06 13:32
浏览 89

在foreach循环中将元素添加到关联数组

I'm creating my own API for an Android app but I cant seem to be able to solve this. (Note this is my first php project).

What I am trying to achieve is to add an element to an associative array and then encode it to JSON but instead the only thing I have achieved is to encode the JSON each time the loop repeats resulting in a bad formatted JSON.

This is the function with the loop

function checkLike($media_id, $user1_id, $access_token){

    $url = 'https://api.instagram.com/v1/media/'.$media_id.'/likes?access_token='.$access_token;

    $json1 = file_get_contents($url);

    $arr1 = json_decode($json1);

    $arr = array('media_id' => $media_id, 'hasLiked' => 0);


    if(is_array($arr1->data)){      
        foreach ($arr1->data as $key => $value) {
            //echo 'Comprobando el id '.$value->id.' deberia ser '. $user1_id.' ';

            if($value->id === $user1_id){
                $arr = array('media_id' => $media_id, 'hasLiked' => 1);
            }else{
                echo 'nope';
            }

        }encode_json($arr);
    }else{
        echo 'false1';
    }

}

and this is the other loop it's being called from

$json = file_get_contents('https://api.instagram.com/v1/users/self/media/recent/?access_token='.$token.'&count=5');

$arr = json_decode($json);



if (is_array($arr->data)) {
    foreach ($arr->data as $key => $value) {
        checkLike($value->id, get_user_id($user, $token), $token);
    }
}

However, the JSON I get is the following:

{"media_id":"1198059901794013237_483636171","hasLiked":0}
{"media_id":"1196611512178987610_483636171","hasLiked":1}
{"media_id":"1195162888588906891_483636171","hasLiked":1}
{"media_id":"1193726158308528216_483636171","hasLiked":1}
{"media_id":"1192260158916546943_483636171","hasLiked":1}

What do I have to do to get something like this?

{
   "photos":[
      {
         "mediaID":"1198059901794013237_483636171",
         "hasLiked":0
         }, {
         "mediaID":"1196611512178987610_483636171",
         "hasLiked":1
         }
   ]
}
  • 写回答

3条回答 默认 最新

  • dongzhuzhou4504 2016-03-06 13:42
    关注

    Just replace this line:

    json_encode($arr);
    

    With:

    json_encode(array("photos"=>$arr));
    
    评论

报告相同问题?

悬赏问题

  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊