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
}
]
}