This is my current Array
Array
(
[0] => [10,13],
[1] => [11,15],
[2] => [12,7],
[3] => [1,0],
[4] => [2,0],
[5] => [3,0],
[6] => [4,0],
[7] => [5,0],
[8] => [6,0],
[9] => [7,0],
[10] => [8,0],
[11] => [9,0]
);
I want to sort this array by the value(value before comma).
Result should be like this:
Array
(
[1] => [1,0],
[2] => [2,0],
[3] => [3,0],
[4] => [4,0],
[5] => [5,0],
[6] => [6,0],
[7] => [7,0],
[8] => [8,0],
[9] => [9,0],
[10] => [10,13],
[11] => [11,15],
[12] => [12,7]
);
Is it possible in PHP ?
OPTION 1 : IF TWO DIMENSIONAL ARRAY TRY THIS ONE
$data = array();
$data[0] = array(10, 13);
$data[2] = array(11, 15);
$data[3] = array(12, 7);
$data[4] = array(1, 0);
$data[5] = array(2, 0);
$data[6] = array(3, 0);
$data[7] = array(4, 0);
$data[8] = array(5, 0);
$data[9] = array(6, 0);
$data[10] = array(7, 0);
$data[11] = array(8, 0);
$data[12] = array(9, 0);
echo "<pre>";
//print_r($data);
array_multisort($data);
print_r($data);
echo "</pre>";
?>
OUTPUT
Array
(
[0] => Array
(
[0] => 1
[1] => 0
)
[1] => Array
(
[0] => 2
[1] => 0
)
[2] => Array
(
[0] => 3
[1] => 0
)
[3] => Array
(
[0] => 4
[1] => 0
)
[4] => Array
(
[0] => 5
[1] => 0
)
[5] => Array
(
[0] => 6
[1] => 0
)
[6] => Array
(
[0] => 7
[1] => 0
)
[7] => Array
(
[0] => 8
[1] => 0
)
[8] => Array
(
[0] => 9
[1] => 0
)
[9] => Array
(
[0] => 10
[1] => 13
)
[10] => Array
(
[0] => 11
[1] => 15
)
[11] => Array
(
[0] => 12
[1] => 7
)
)
OPTION 2 : IF ONE DIMENSIONAL ARRAY TRY THIS ONE
$data = array();
$data[0] = "10,13";
$data[2] = "11,15";
$data[3] = "12,7";
$data[4] = "1,0";
$data[5] = "2,0";
$data[6] = "3,0";
$data[7] = "4,0";
$data[8] = "5,0";
$data[9] = "6,0";
$data[10] = "7,0";
$data[11] = "8,0";
$data[12] = "9,0";
echo "<pre>";
//print_r($data);
echo "</pre>";
function dataSort($data){
$data_temp =array();
foreach($data as $item){
$data_temp[] = explode(",",$item);
}
array_multisort($data_temp);
$data =array();
foreach($data_temp as $item){
$data[] = $item[0].",".$item[1];
}
return $data;
}
$data = dataSort($data);
print_r($data);
OUTPUT
Array
(
[0] => 1,0
[1] => 2,0
[2] => 3,0
[3] => 4,0
[4] => 5,0
[5] => 6,0
[6] => 7,0
[7] => 8,0
[8] => 9,0
[9] => 10,13
[10] => 11,15
[11] => 12,7
)
Try this
function mSort($a,$b) {
if ($a[0] == $b[0]) {
return 0;
}
return ($a[0] < $b[0]) ? -1 : 1;
}
usort($arr, "mSort");
print_r($arr);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With