我有这段代码:
<?php
$sort = array(1.5, 3.4, 2.1, 4.9, 5.7, 6.3);
sort($sort);
$tampil=array('abc','hoho','hah','something','lol','nice');
$tampil2=array('wait','wush','wicked','who','why','what');
for ($i = 0; $i < count($sort); $i++) {
echo $i.'_<strong>'.$sort[$i].'</strong>';
echo '_'.$tampil[$i].'_';
echo $tampil2[$i].' <br />';
}
?>
结果是:
0_1.5_abc_wait
1_2.1_hoho_wush
2_3.4_hah_wicked
3_4.9_something_who
4_5.7_lol_why
5_6.3_nice_what
我想要的是$tampil[$i]
将根据排序的$sort
显示,$tampil2[$i]
($i
'也会跟随{{1}在$i
)中。
就像这样,我希望它出现:
$sort
我尝试0_1.5_abc_wait
1_2.1_hah_wicked //$tampil and $tampil2's positions change by the sorted $sort
2_3.4_hoho_wush
3_4.9_something_who
4_5.7_lol_why
5_6.3_nice_what
和multisort
来解决这个问题。但这似乎是我难以解决的逻辑。我似乎没有通过上面的标题在Google和StackOverFlow中查询找到解决方案。
需要帮忙。 :)谢谢..
答案 0 :(得分:0)
这就是你要找的东西! array_multisort
array_multisort($sort, $tampil, $tampil2);
array_multisort
排序第一个数组并根据第一个
0_1.5_abc_wait
1_2.1_hah_wicked
2_3.4_hoho_wush
3_4.9_something_who
4_5.7_lol_why
5_6.3_nice_what
答案 1 :(得分:0)
<?php
$sort = array(1.5, 3.4, 2.1, 4.9, 5.7, 6.3);
$sort_dup = $sort;
sort($sort_dup);
$tampil=array('abc','hoho','hah','something','lol','nice');
$tampil2=array('wait','wush','wicked','who','why','what');
$i = 0;
foreach($sort_dup as $sorted) {
$key = array_search($sorted, $sort);
echo $i."_".$sorted."_".$tampil[$key]."_".$tampil2[$key]."<br />";
}
?>
好吧,我创建了一个副本并对其进行了排序。在循环时,它从原始数组获取键并打印出其他2个数组元素的值。它具有与array_multisort()
PHP函数相同的逻辑和工作。
答案 2 :(得分:0)
像这样排序
<?php
$sort = array(1.5, 3.4, 2.1, 4.9, 5.7, 6.3);
$tampil=array('abc','hoho','hah','something','lol','nice');
$tampil2=array('wait','wush','wicked','who','why','what');
array_multisort($sort, SORT_ASC, SORT_REGULAR, $tampil, $tampil2);
var_dump($sort, $tampil, $tampil2);
答案 3 :(得分:0)
如果您像这样格式化数组,可以在项目上使用ksort
,然后轻松地遍历它们。
注意:您的密钥1.5, 3.4, etc.
需要为字符串才能生效。
像这样:
<?php
$sort = array(
"1.5" => array(
"abc",
"wait"
),
"3.4" => array(
"hoho",
"wush"
),
"2.1" => array(
"hah",
"wicked"
),
"4.9" => array(
"something",
"who"
),
"5.7" => array(
"lol",
"why"
),
"6.3" => array(
"nice",
"what"
)
);
ksort($sort);
$i = 0;
foreach($sort as $key => $value){
echo "{$i}_{$key}_{$value[0]}_{$value[1]}\n";
$i++;
}
最终输出将如下所示:
0_1.5_abc_wait
1_2.1_hah_wicked
2_3.4_hoho_wush
3_4.9_something_who
4_5.7_lol_why
5_6.3_nice_what