下面给出的是我的数组结构
Array
(
[0] => Array
(
[product_id] => 59
[product_name] => Samsung Champ DUOS E2652
[product_price] => 4439
[sub_cat_name] => Samsung
[sub_cat_url] => samsung
[image] => samsung-champ-duos-e2652---1414801404364308.jpg
[currency] => ₹
)
[1] => Array
(
[product_id] => 195
[product_name] => Samsung Galaxy Tab 4 7.0
[product_price] => 17847
[sub_cat_name] => Samsung
[sub_cat_url] => samsung
[image] => galaxy-tab-4-7-0---1715601405057269.png
[currency] => ₹
)
[2] => Array
(
[product_id] => 284
[product_name] => Samsung Galaxy Tab 3 Lite 7.0
[product_price] => 18000
[sub_cat_name] => Samsung
[sub_cat_url] => samsung
[image] => galaxy-tab-3-lite-7-0---1590061405576878.png
[currency] => ₹
)
[3] => Array
(
[product_id] => 19
[product_name] => Samsung Galaxy Star
[product_price] => 4833
[sub_cat_name] => Samsung
[sub_cat_url] => samsung
[image] => feature-img144811404109906.jpg
[currency] => ₹
)
[4] => Array
(
[product_id] => 186
[product_name] => Samsung Galaxy S5 Active
[product_price] => 31922
[sub_cat_name] => Samsung
[sub_cat_url] => samsung
[image] => galaxy-s5-active368091404989896.png
[currency] => ₹
)
)
我想基于sub_cat_url
排序此数组,如下所示
array
(
[0] => samsung
[0] => Array
(
[product_id] => 186
[product_name] => Samsung Galaxy S5 Active
[product_price] => 31922
[sub_cat_name] => Samsung
[sub_cat_url] => samsung
[image] => galaxy-s5-active368091404989896.png
[currency] => ₹
)
[1] => Array
(
[product_id] => 284
[product_name] => Samsung Galaxy Tab 3 Lite 7.0
[product_price] => 18000
[sub_cat_name] => Samsung
[sub_cat_url] => samsung
[image] => galaxy-tab-3-lite-7-0---1590061405576878.png
[currency] => ₹
)
)
因为我写了下面的代码。
for($i = 0; $i < $count; $i++){
if($i == 0){
$search_array[$i] = $search_data[$i]["sub_cat_name"];
$search_array[$i] = $search_data[$i]["product_name"];
$j += 1;
}
else if($search_data[$i]["sub_cat_url"] !== $search_data[$i]["sub_cat_url"]){
$search_array[$i] = array($search_data[$i]["sub_cat_name"]);
$search_array[$i] = array($search_data[$i]["product_name"]);
$j += 1;
}
else if($search_data[$i]["sub_cat_url"] === $search_data[$i]["sub_cat_url"]){
$search_array[$i] = array($search_data[$i]["product_name"]);
$j += 1;
}
}
但效果不佳。我也尝试使用内部for循环。它也没有给我实际的结果。有人可以请我为此编写正确的循环语句吗? 提前谢谢
答案 0 :(得分:1)
如果我理解你这应该有效:
$out = array();
$map = array();
foreach ($array as $k => $v) {
$url = $v['sub_cat_url'];
if (!isset($map[$url])) {
$map[$url] = count($out);
}
$out[$map[$url]][$url][$k] = $v; // or $out[$map[$url]][$url][] = $v;
}
但是我没有测试过(你没有提供PHP格式的数据)