PHP如何简化复杂的大数组
嗨,我想让复杂数组在视图中简单使用 然而,我有点陷入了一个循环 请看我对数组的误解 我希望这个数组简单PHP如何简化复杂的大数组,php,arrays,Php,Arrays,嗨,我想让复杂数组在视图中简单使用 然而,我有点陷入了一个循环 请看我对数组的误解 我希望这个数组简单 'collection' => [ (int) 0 => [ 'type' => 'col', 'name' => '2016 F/W', 'url' => 'blablabla' ], (int) 1 => [ 'type' => 'col', '
'collection' => [
(int) 0 => [
'type' => 'col',
'name' => '2016 F/W',
'url' => 'blablabla'
],
(int) 1 => [
'type' => 'col',
'name' => '2015 F/W',
'url' => 'blablabla'
],
(int) 2 => [
'type' => 'project',
'name' => '2015 F/W',
'url' => 'blablabla'
]
]
我想要这样的数组
[
(int) 0 => [
'type' => 'col',
'type2' => [
(int) 0 => [
'name' => '2016 F/W',
'image' => [
(int) 0 => [
'url' => null
],
(int) 1 => [
'url' => null
]
]
],
(int) 1 => [
'name' => '2015 F/W',
'image' => [
(int) 0 => [
'url' => null
]
]
]
]
],
(int) 1 => [
'type' => 'project',
'type2' => [
(int) 0 => [
'name' => '2015 F/W',
'image' => [
(int) 0 => [
'url' => null
]
]
],
]
]
请帮忙!!我快疯了 我得说结果数组看起来不是很有用。 由于没有太多关于这项任务目标的信息,我只提供我对如何完成这项任务的看法
$arr = array(
'collection' => array(
array(
'type' => 'col',
'name' => '2016 fw',
'url' => 'blabla1'
),
array(
'type' => 'col',
'name' => '2015 F/W',
'url' => 'blabla2'
),
array(
'type' => 'project',
'name' => '2015 F/W',
'url' => 'blabla_project'
),
),
);
// $types array will hold a list of all types. type in this
// example is 'col' and 'project'.
// we will use $types to find if type X was already added to the
// result array.
$types = array();
// Every type X will be in the result array in key K, So $typesMap
// will map between the type to the key in the result array.
// Example: type X is located in the result array under key K
// So I can find the type X data by looking at the
// $resultArr[K]
$typesMap = array();
$typeIndx = 0;
// This is the result array.
$resultArr = array();
// run over all collections
foreach($arr['collection'] as $collection){
// get the current type. e.g 'col'
$type = $collection['type'];
// Search the $types array for 'col' to see if it was defined
// already.
if(!in_array($type, $types)) {
// if it wasn't defined then define it now:
// add it to the $types array so that we can find it on
// the next run.
$types[] = $type;
// define the key (K) that it will be in the $resultArr
$typesMap[$type] = $typeIndx;
// Create the 'col' key in the result array.
$resultArr[$typeIndx] = array('type' => $type, 'type2' => array());
$typeIndx++;
}
// get the key for type $type.
// remember? I can use the $typesMap to find the type's index
// in the result array.
$currentIndx = $typesMap[$type];
// add the extra data to the 'type2' (not a very good name for
// this)
$resultArr[$currentIndx]['type2'][] = array(
'name' => $collection['name'],
'image' => $collection['url']
);
}
我真的不理解结果数组的url部分。原点是第一个,结果是最后一个。你在做什么循环以使其看起来像这样,你必须提供一些代码,因为人们不能只知道你做了什么。如果第二个是结果,而不是如何从单个字符串创建多个图像url?哦,对不起,我不是这个意思。它不应该是多个urlsThanks,它帮助了我很多,但我解释得很糟糕。这很好,但我在阅读你的代码时遇到了麻烦。我一点也不懂你的代码。有什么高级关联数组练习适合我吗?理解你的代码?谢谢你的评论。你应该试着调试它。xdebug?谢谢!!!那些评论太有用了!!