【问题标题】:How to split array into two different array based on value?如何根据值将数组拆分为两个不同的数组?
【发布时间】:2018-06-17 03:07:06
【问题描述】:

我有一个如下所示的数组

array:2 [▼
  0 => array:2 [▼
    "id" => 0
    "item_code" => "abc001"
  ]
  1 => array:2 [▼
    "id" => 1
    "item_code" => "abc002"
  ]
]

当 id = 0 时如何将其拆分为新数组?

// $newArr to store id = 0
0 => array:2 [▼
   "id" => 0
   "item_code" => "abc001"
]
// $oldArr to store id != 0
1 => array:2 [▼
   "id" => 1
   "item_code" => "abc002"
]

我想将每个 id = 0 存储到 $newArr 并将 id !=0 存储到 $oldArr。

【问题讨论】:

    标签: php arrays laravel


    【解决方案1】:

    如果你的 $array 是一个集合,那么试试where()-

    $new_array = $array->where('id','=',0);
    $old_array = $array->where('id','!=',0);
    

    如果它是一个数组,则首先使用 collect()- 将其设为一个集合-

    $array = collect($array);
    

    【讨论】:

    • 请解释一下代码...我的代码出错了...请告诉我它是如何工作的...?
    • 我们可以使用 laravel 提供的 where() 方法通过集合对象进行查询。请查看此链接laravel.com/docs/5.5/collections#method-where
    • 好的...这是 laravel 项目...我在 core php 运行它...没有问题...谢谢...
    • 为什么它显示我在刀片中循环时尝试获取非对象错误的属性?是否返回空值然后导致错误?
    • 试试 dd($single_object) 看看你的循环
    【解决方案2】:

    您可以使用收集方法。首先,包装你的数组:

    $collection = collect($array);
    

    1.使用where()

    @foreach ($collection->where('id', 0) as $item)
        {{ $item['item_code'] }}
    @endforeach
    
    @foreach ($collection->where('id', '!=', 0) as $item)
        {{ $item['item_code'] }}
    @endforeach
    

    2.使用partition()

    list($idIsZero, $idIsNotZero) = $collection->partition(function ($i) {
        return $i['id'] === 0;
    });
    

    在大多数情况下,您不需要将集合转换回数组,但如果需要,请在集合上使用 ->toArray()

    【讨论】:

      【解决方案3】:

      输入

      $array = array(
          array("id" => 0,"item_code" => "abc001"),
          array("id" => 1,"item_code" => "abc002")
      );
      

      解决方案

      $oldArray = array();
      $newArray = array();
      foreach($array as $row){
          if($row['id']==0)$oldArray[] = $row;
          else $newArray[] = $row;
      }
      echo "New<pre>";print_r($newArray);echo "</pre>";
      echo "Old<pre>";print_r($oldArray);echo "</pre>";
      

      输出

      New
      Array
      (
          [0] => Array
              (
                  [id] => 1
                  [item_code] => abc002
              )
      
      )
      Old
      Array
      (
          [0] => Array
              (
                  [id] => 0
                  [item_code] => abc001
              )
      
      )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-12-04
        • 2014-07-31
        • 2017-05-27
        • 2021-05-25
        • 1970-01-01
        • 1970-01-01
        • 2021-01-27
        • 2011-06-15
        相关资源
        最近更新 更多