【问题标题】:Laravel php get last element in multidimensional arrayLaravel php获取多维数组中的最后一个元素
【发布时间】:2017-09-02 05:23:10
【问题描述】:

我有以下包含产品详细信息的 json 文件:

  "products": [
    {
      "sku": 123,
      "name": "iphone 7",
      "categoryPath": [
        {
          "id": "abcat0800000",
          "name": "Cell Phones"
        },
        {

          "id": "pcmcat209400050001",
          "name": "All Cell Phones with Plans"

        }
      ],
}
]

我只想存储 categoryPath 数组的最后一个值(ID 和 NAME):

          "id": "pcmcat209400050001",
          "name": "All Cell Phones with Plans"

我当前的代码获取 json 文件,解码 json 并在产品表中插入信息。

    $json = File::get("/json/cell-0.json");
    $data = json_decode($json);
    $array1 = (array)$data;
    //table products
    foreach ($array1['products'] as $obj) {
        DB::table('products')->insert(array(
            'productSku' => ((isset($obj->sku) ? $obj->sku : 1)),
            'productName' => ((isset($obj->name) ? $obj->name : null)),
            'categoryId' => end($obj->categoryPath->id),
            'categoryName' => end($obj->categoryPath->name)
        ));

考虑到 array->categoryPath 有多个字段,我想使用一个函数(例如:end())来获取最后一个值的 id 和 name。

使用 end($obj->categoryPath->id) 我收到以下错误 ->

尝试修改非对象的属性

这是检索多维数组最后一个值的最佳方法吗?

【问题讨论】:

    标签: php arrays json laravel-5


    【解决方案1】:

    您可能可以使用 end(),但您的访问器必须在 end() 调用之外(未经测试):

        foreach ($array1['products'] as $obj) {
    
        DB::table('products')->insert(array(
            'productSku' => ((isset($obj->sku) ? $obj->sku : 1)),
            'productName' => ((isset($obj->name) ? $obj->name : null)),
            'categoryId' => end($obj->categoryPath)->id,
            'categoryName' => end($obj->categoryPath)->name
        ));
    

    【讨论】:

      【解决方案2】:

      您获取最后一个元素的方式不正确,这是重构的代码。我还消除了将数据转换为数组的需要。

      $json = File::get("/json/cell-0.json");
      $data = json_decode($json, true);
      //table products
      foreach ($data['products'] as $product) {
          $lastCategory = isset($product['categoryPath']) && $size = sizeof($product['categoryPath']) ? $product['categoryPath'][$size-1] : array('id' => null, 'name' => null);
          DB::table('products')->insert(
              array(
                  'productSku' => isset($product['sku']) ? $product['sku'] : 1,
                  'productName' => isset($product['name']) ? $product['name'] : null,
                  'categoryId' => lastCategory['id'],
                  'categoryName' => lastCategory['name']
              )
          );
      }
      

      【讨论】:

      • 我试过这个例子。在 $lastCategory 的第二部分中未检测到 $size。另一种选择更简单。非常感谢@Augwa
      猜你喜欢
      • 2021-12-27
      • 2014-09-27
      • 2012-11-03
      • 1970-01-01
      • 2012-03-31
      • 2011-07-25
      • 2016-11-26
      • 2022-09-29
      • 2011-01-12
      相关资源
      最近更新 更多