【问题标题】:Issue creating JSON feed in Laravel在 Laravel 中创建 JSON 提要的问题
【发布时间】:2019-12-12 19:52:08
【问题描述】:

我正在尝试使用下面提到的格式的两个数据数组创建 JSON 提要。

{ 
   "items":[ 
      { 
         "category_id":1,
         "category_name":"Mens Clothing",
         "child":[ 
            { 
               "product_id":1,
               "product_name":"Shirts"
            },
            { 
               "product_id":2,
               "product_name":"T-Shirts"
            }
         ]
      }
   ]
}

但是,我的情况如下。

{ 
   "items":[ 
      { 
         "category_id":1,
         "category_name":"Mens Clothing",
         "child":[ 

         ]
      }
   ],
   "child":[ 
      { 
         "product_id":1,
         "product_name":"Shirts"
      },
      { 
         "product_id":2,
         "product_name":"T-Shirts"
      }
   ]
}

我在 Laravel 中写了以下内容。

$data = [
    'items' => [],
];

foreach ($categories as $key => $category) {
    $data['items'][$key] = [
        'category_id' => $category->id,
        'category_name' => $category->category_name,
        'child' => [],
    ];
}

foreach ($products as $key => $product) {
    $data['child'][$key] = [
        'product_id' => $product->id,
        'product_name' => $product->product_name
    ];
}

谁能帮我解决这个问题?

【问题讨论】:

  • categoriesproducts之间有关系吗?
  • 是的!类别和产品之间存在关系。两个表都有 category_id。
  • 如果你使用 eloquent 模型,你应该能够定义一个不错的干净 eloquent api resource 并跳过所有循环。

标签: arrays json laravel laravel-6


【解决方案1】:

如果产品有 'category_id' - 类似下面的东西可以工作:

$data = [
    'items' => [],
];

foreach ($categories as $key =>  $category) {
    $children = [];
    foreach ($products as $key => $product){
        if($product->category_id == $category->id) {
            $children[] = $product;
        }
    }
    $data['items'][$key] = [
        'category_id' => $category->id,
        'category_name'=> $category->category_name,
        'child' => $children,
    ];
}

【讨论】:

  • 感谢安加德的帮助!
猜你喜欢
  • 1970-01-01
  • 2017-11-18
  • 1970-01-01
  • 1970-01-01
  • 2022-01-05
  • 1970-01-01
  • 2016-08-27
  • 2021-04-08
  • 2011-06-08
相关资源
最近更新 更多