我有一個包含欄位的陣列
[
"house" => "30|30|30",
"street" => "first|second|third",
...
]
我想得到陣列
[
[
"house" => "30",
"street" => "first",
...
],
[
"house" => "30",
"street" => "second",
...
],
[
"house" => "30",
"street" => "third",
...
]
]
我知道如何使用 PHP 和回圈來解決這個問題,但也許這個問題有更漂亮的解決方案
uj5u.com熱心網友回復:
這是我設法用修補匠做的事情。
$original = [
"house" => "30|30|30",
"street" => "first|second|third",
];
$new = []; // technically not needed. data_set will instantiate the variable if it doesn't exist.
foreach ($original as $field => $values) {
foreach (explode('|', $values) as $index => $value) {
data_set($new, "$index.$field", $value);
}
}
/* dump($new)
[
[
"house" => "30",
"street" => "first",
],
[
"house" => "30",
"street" => "second",
],
[
"house" => "30",
"street" => "third",
],
]
*/
我嘗試使用集合,但主要問題是原始陣列的長度不等于結果陣列的長度,因此映射操作實際上不起作用。我想你仍然可以使用each。
$new = []; // Since $new is used inside a Closure, it must be declared.
collect([
"house" => "30|30|30",
"street" => "first|second|third",
...
])
->map(fn($i) => collect(explode('|', $i))
->each(function ($values, $field) use (&$new) {
$values->each(function ($value, $index) use ($field, &$new) {
data_set($new, "$index.$field", $value);
});
});
uj5u.com熱心網友回復:
使用拉鏈
$data = [
"house" => "30|30|30",
"street" => "first|second|third",
];
$house = collect(explode('|',$data['house']));
$street = collect(explode('|',$data['street']));
$out = $house->zip($street);
$out->toarray();
uj5u.com熱心網友回復:
$array = ["house" => "30|30|30","street" => "first |second| third"];
foreach($array as $key=> $values){
$explodeval = explode('|',$values);
for($i=0; $i<count($explodeval); $i ){
$newarray[$i][$key]= $explodeval[$i];
}
}
輸出:
陣列 ( [0] => 陣列 ( [house] => 30 [street] => first )
[1] => Array
(
[house] => 30
[street] => second
)
[2] => Array
(
[house] => 30
[street] => third
)
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/447376.html
上一篇:如何在登錄時排除用戶角色被更改?
