我使用Core PHP在API中使用JSON输出产品列表,这里我需要在输出中进行一些修正。我只想在数组键中使用'body','dishes'和'dish_details'而不想将产品ID 18,26等显示为数组键。
如果我从循环中删除[$nid]
,则仅打印最后的产品详细信息。
请参阅下面的代码:
foreach ($nodes as $nid => $node) {
$output['dishes'][$nid]['dish_details']['dish_title'] = $node->title;
$output['dishes'][$nid]['dish_details']['dish_image'] = $node->field_recipe_entities[$node->field_recipe]->field_recipe_image_url;
$output['dishes'][$nid]['dish_details']['dish_price'] = $node->field_recipe_entities[$node->field_recipe]->commerce_price_formatted;
$output['dishes'][$nid]['dish_details']['dish_rating'] = $node->rating;
$output['dishes'][$nid]['dish_details']['dish_desc'] = $node->desc;
$output['dishes'][$nid]['dish_details']['dish_type'] = $node->type;
$output['dishes'][$nid]['dish_details']['dish_location'] = $node->location;
}
$return = new stdClass();
$return->body = $output;
$return->message = "Dish list retrieved successfully.";
$return->error = 'nil';
$return->status = 200;
并查看我的输出:
{
"body":{
"dishes":{
"18":{
"dish_details":{
"dish_id":"18",
"product_id":"25",
"dish_title":"Cogo Laoreet Roto",
"dish_image":"http://localhost/drupal739/sites/default/files/dish_images/ima7070.tmp.png",
"dish_price":"189.53 INR",
"dish_rating":"",
"dish_desc":{
"value":"Capto luctus nobis oppeto pagus torqueo veniam. Dolore eros hendrerit. Consectetuer genitus iaceo quia sed. Caecus commoveo dignissim elit melior modo refoveo tego vicis.\n\n",
"summary":null,
"format":"full_html",
"safe_value":"<p>Capto luctus nobis oppeto pagus torqueo veniam. Consectetuer genitus iaceo quia sed. Caecus commoveo dignissim elit melior modo refoveo tego vicis.</p>\n",
"safe_summary":""
},
"dish_type":"",
"dish_location":""
}
},
"26":{
"dish_details":{
"dish_id":"26",
"product_id":"8",
"dish_title":"Obruo Quibus",
"dish_image":null,
"dish_price":"500.00 INR",
"dish_rating":"",
"dish_desc":{
"value":"Amet aptent brevitas caecus commoveo consequat populus si. Distineo dolor esca gemino importunus metuo paratus tincidunt wisi.\n\n",
"summary":null,
"format":"full_html",
"safe_value":"<p>Amet aptent brevitas caecus commoveo consequat populus si. Distineo dolor esca gemino importunus metuo paratus tincidunt wisi.</p>\n",
"safe_summary":""
},
"dish_type":"",
"dish_location":""
}
}
}
}
}
任何人都有任何解决方案,请在这里分享。
答案 0 :(得分:0)
实际上你正在迭代foreach,你需要为每个节点提供索引,这样它们就不会覆盖这些值。
天气指定数组开头或中间的索引
$ouput[]['dishes']['anotherindex']['title'] = value;
将打印类似
的内容0 : {
"dishes" : {
"anotherindex" : {
"title" : {
values here
答案 1 :(得分:0)
如果您使用的是PHP 5.5并且想要搜索特定元素,那么您可以在没有循环的情况下使用以下内容:
//If 18 is one of the dishes key
$key = array_search('18', array_column($data['body'], 'dishes'));
if ($key !== false) {
//Do something with that array segment
var_dump($data['body'][$key]);
}