0 "item_code" => "abc001" ] 1 => array:-6ren">
gpt4 book ai didi

php - 如何根据值将数组拆分为两个不同的数组?

转载 作者:行者123 更新时间:2023-12-03 18:45:39 27 4
gpt4 key购买 nike

我有一个如下所示的数组

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 中。

最佳答案

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

$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()

关于php - 如何根据值将数组拆分为两个不同的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48145180/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com