这是我的数组代码示例,我需要在没有内置函数的情况下进行排序,我尝试了 2 个循环,但看起来我没有得到这个程序的正确输出,请检查并给我可能的解决方案,如果你有......
$my_array = array(
'51171#2' => array(
'my_id' => 51171,
'variation_id' => 2,
),
'143516#2' => array(
'my_id' => 143516,
'variation_id' => 2,
),
'396346#2' => array(
'my_id' => 396346,
'variation_id' => 2,
),
'143516#1' => array(
'my_id' => 143516,
'variation_id' => 1,
),
'396344#2' => array(
'my_id' => 396344,
'variation_id' => 2,
),
'396346#1' => array(
'my_id' => 396346,
'variation_id' => 1,
),
'396344#1' => array(
'my_id' => 396344,
'variation_id' => 1,
),
);
上面是我的示例数组,所以在这里我想按 my_id 排序,而不使用 php 内置函数。我想要这样的输出:-
$output_arr = array(
'143516#2' => array(
'my_id' => 143516,
'variation_id' => 2,
),
'143516#1' => array(
'my_id' => 143516,
'variation_id' => 1,
),
'396344#2' => array(
'my_id' => 396344,
'variation_id' => 2,
),
'396344#1' => array(
'my_id' => 396344,
'variation_id' => 1,
),
'396346#2' => array(
'my_id' => 396346,
'variation_id' => 2,
),
'396346#1' => array(
'my_id' => 396346,
'variation_id' => 1,
),
'51171#2' => array(
'my_id' => 51171,
'variation_id' => 2,
),
);
所以我尝试代码:-
$result = [];
foreach($my_array as $key => $source){
foreach($my_array as $key1 => $source1){
if(($source['my_id'] < $source1['my_id']))
{
$result[$key1]= $source1;
}
}
}
echo '<pre>';
print_r($result);
输出:-
Array
(
[143516#2] => Array
(
[my_id] => 143516
[variation_id] => 2
)
[396346#2] => Array
(
[my_id] => 396346
[variation_id] => 2
)
[143516#1] => Array
(
[my_id] => 143516
[variation_id] => 1
)
[396344#2] => Array
(
[my_id] => 396344
[variation_id] => 2
)
[396346#1] => Array
(
[my_id] => 396346
[variation_id] => 1
)
[396344#1] => Array
(
[my_id] => 396344
[variation_id] => 1
)
)
但这不是正确的输出,请帮我解决这个问题。