下面的代码返回我需要的格式,但它不能动态工作,这意味着如果用户不想要"id",那么它也返回"id"值。为了更好地理解,我将显示我的输入 json 对象,其中用户请求他需要的字段。这是输入 json
Input:
{
"session_id": "cj9f28hf29",
"post_id": "91024",
"fields": "id, image_urls, tagged_users, has_liked, has_commented"
}
我必须检查"字段"键并仅返回请求的字段。这是我写的代码,任何人都可以帮助我使其动态化。
while ($row = $get_postid->fetch_array())
{
$id=$row['post_id'];
$image_urls=explode(',',$row['post_image_url']);
$storetag= explode(',',$row['post_tagged_id']);
$has_liked="false";
$has_commented="false";
}
for($i=0;$i<count($storetag);$i++)
{
$user=mysqli_query($con,"select user_id, profile_image_url from Wheel_User where user_id='$storetag[$i]'");
if(mysqli_num_rows($user)==0)
{
//For failure status if session id is wrong.
http_response_code(500);
echo json_encode(array("error_code"=>"500","error_message"=>"Sorry, post id does not exists.".die()));
}
else
{
while ($row = $user->fetch_array())
{
$tagged_users[$i]['id']=$row['user_id'];
$pro_image_url[$i]=$row['profile_image_url'];
$short_image_url[$i]=str_replace('_b','_t',$pro_image_url[$i]);
$short_image_url[$i]=str_replace('/images/','/thumbnails/',$short_image_url[$i]);
$tagged_users[$i]['short_image_url']=$short_image_url[$i];
}
}
}
echo str_replace(''/','/', json_encode(array("id"=>$id,"image_urls"=>$image_urls,"tagged_users"=>$tagged_users,"has_liked"=> $has_liked,"has_commented"=>$has_commented)));
}
}
}
我在 json 的输出中为 ex:"id"=> 硬编码键名,但它必须是动态的。 请帮我解决这个问题。提前谢谢你。
如果您能够将输入 JSON 重构为数组,则更像
{
"foo":"bar",
"fields":['id', 'image_urls', 'tagged_users', 'has_liked', 'has_commented']
}
那么你也许可以做一些类似的事情
rowFields = ["id","profile_image_url"]
shortFields=["shortImageUrl"]
for $j = 0; j< $input.fields.count();j++{
if(in_array(fields[$j],rowFields)){
$tagged_users[$i][fields[$j]]=$row[fields[$j]];
} else {
if(in_array(fields[$j],shortFields)){
$tagged_users[$j][fields[$j]]=$short_image_url[fields[$j]];
}
}
}
非常头顶,但希望你明白要点!
本以为您可以对需要从中提取数据的任意数量的单独表重复此模式。