这是我拥有的数组。
Array
(
[0] => name:string:255
[1] => weight:integer
[2] => description:string:255
[3] => age:integer
)
我希望它看起来像这样
NewArray
(
[0] => Array
(
[0] => name
[1] => string
[2] => 255
[1] => Array
(
[0] => weight
[1] => integer
[2] => Array
(
[0] => description
[1] => string
[2] => 255
[3] => Array
(
[0] => age
[1] => integer
)
或者更好的是,我更喜欢这个结果。根据组的数量制作两个独立的数组。
NewArray1
(
[0] => Array
(
[0] => name
[1] => string
[2] => 255
[1] => Array
(
[0] => description
[1] => string
[2] => 255
)
NewArray2
(
[0] => Array
(
[0] => weight
[1] => integer
[1] => Array
(
[0] => age
[1] => integer
)
我已经尝试过爆炸,内爆和预告,但我并没有得到我想要的结果。先谢谢!
答案 0 :(得分:2)
使用array_reduce()
构建一个新数组,同时迭代旧数组,按类型拆分:
$array = [
'name:string:255',
'weight:integer',
'description:string:255',
'age:integer',
];
$result = array_reduce($array, function(&$result, $item) {
$parts = explode(':', $item, 3);
$result[$parts[1]][] = $parts;
return $result;
}, []);
答案 1 :(得分:1)
试试这个:
<?php
$array = array("name:string:255", "weight:integer", "description:string:255", "age:integer");
function map_func($value) {
return explode(':', $value);
}
$newArray = array_map(map_func, $array);
echo "Output 1:\n";
print_r($newArray);
$sorted = array();
foreach($newArray as $el)
$sorted[$el[1]][] = $el;
echo "Output 2:\n";
print_r($sorted);
Output 1:
Array
(
[0] => Array
(
[0] => name
[1] => string
[2] => 255
)
[1] => Array
(
[0] => weight
[1] => integer
)
[2] => Array
(
[0] => description
[1] => string
[2] => 255
)
[3] => Array
(
[0] => age
[1] => integer
)
)
Output 2:
Array
(
[string] => Array
(
[0] => Array
(
[0] => name
[1] => string
[2] => 255
)
[1] => Array
(
[0] => description
[1] => string
[2] => 255
)
)
[integer] => Array
(
[0] => Array
(
[0] => weight
[1] => integer
)
[1] => Array
(
[0] => age
[1] => integer
)
)
)
答案 2 :(得分:1)
我怀疑以下是最佳解决方案,但它确实会返回您想要的内容。
$array = array(
"0" => "name:string:255",
"1" => "weight:integer",
"2" => "description:string:255",
"3" => "age:integer"
);
foreach ($array as $key => $val) {
foreach (explode(':', $val) as $part) {
$new_array[$key][] = $part;
}
}
print_r($new_array);
上面的返回以下内容。
Array
(
[0] => Array
(
[0] => name
[1] => string
[2] => 255
)
[1] => Array
(
[0] => weight
[1] => integer
)
[2] => Array
(
[0] => description
[1] => string
[2] => 255
)
[3] => Array
(
[0] => age
[1] => integer
)
)
答案 3 :(得分:-2)
所以你有一个1维数组的字符串($ arr01)。字符串由:
分隔你需要有一个二维数组($ arr02),其中第二个维是一个字符串数组,它是根据它们的分隔符来分割初始字符串组合的:
$arr01 = array("name:string:255", "weight:integer", "description:string:255", "age:integer");
$arr02 = array(array());
for($i=0; $i<sizeof($arr01); $i++) {
$arr02[$i] = explode(":",$arr01[$i]);
}
显示两个数组......
echo "array 01: <br>";
for($i=0; $i<sizeof($arr01); $i++) {
echo "[".$i."] ".$arr01[$i]."<br>";
}
echo "<br><br>";
echo "array 02: <br>";
for($i=0; $i<sizeof($arr01); $i++) {
echo "[".$i."] ==> <br>";
for($j=0; $j<sizeof($arr02[$i]); $j++) {
echo " [".$j."] ".$arr02[$i][$j]." <br>";
}
}
echo "<br><br>";