【发布时间】:2023-03-06 20:34:01
【问题描述】:
我想重新排序我的元素索引对齐数组,以便我可以获取每个唯一 CATEGORY 的元素,而不是手动按索引。
前置条件
$products = array(
'CATEGORY' =>
array(
0 => 'book',
1 => 'book',
2 => 'desk',
),
/* FYI: Other keys have been removed for conciseness */
'DESCRIPTION' =>
array(
0 => 'Bar',
1 => 'sdfadasfdasfas',
2 => 'Barrrr',
),
);
后置条件
$products = array(
'CATEGORY' =>
array(
'book' =>
array(
0 =>
array(
'DESCRIPTION' => 'Bar',
),
1 =>
array(
'DESCRIPTION' => 'sdfadasfdasfas',
),
),
'desk' =>
array(
0 =>
array(
'DESCRIPTION' => 'Barrrr',
),
),
),
)
尝试
$cat_to_index = '';
foreach (array_values(array_unique($products['CATEGORY'])) as $category => $uniq_cat) {
for($i=array_search($uniq_cat, $products['CATEGORY']);
$i!==FALSE; $i=array_search($uniq_cat, $products['CATEGORY']))
$cat_to_index .= $i; // just for debugging
}
查看在codepad上运行。
错误
内存不足(无限循环)。最好寻找O(n) 解决此问题的方法。
【问题讨论】:
-
另外我不明白为什么这不能在
O(n)中完成,其中n是$products的大小... -
在我的手机上,所以我只是略过一遍:使用 array_keys 然后使用 array_count_values 怎么样?
-
for ($i = array_search(...))- 只是随机地将语法放在一起通常是行不通的......:P -
在 C++ 和 Python 中使用随机语法!