Home > Software design >  Sort multiple arrays by string php
Sort multiple arrays by string php

Time:11-19

I have those arrays , how to sort by string ? Just I need to sort mulltiple arrays I try sort() but no luck it give me error.

    array(1) {
      [0]=>
      string(2) "10"
    }
    
    array(1) {
      [0]=>
      string(1) "2"
    }
    
    array(1) {
      [0]=>
      string(1) "3"
    }
    
    array(1) {
      [0]=>
      string(1) "4"
    }

This is my code now

          <?php
             $myfiles = glob('articol/*');
             foreach($myfiles as $filename){ 
                if(is_file($filename)){
                      $file = file_get_contents($filename);
                      $html = $file;
                      preg_match('/<p  hidden>(.*?)<\/p>/s', $html, $id) // Return 1 or 2 or 3 .... or 10 ; 
                      $idFinal = array($id[1]);

                      sort($idFinal);
                      echo "<pre>"; var_dump($idFinal); echo "</pre>";
                }
             }
          ?>

CodePudding user response:

The sort() function is right.

$a1 = ["10"];
$a2 = ["2"];
$a3 = ["3"];
$a4 = ["4"];

$array = array_merge($a1, $a2, $a3, $a4);

 
$new = array_map(function($e) {
    return (int) $e;
},$array);

sort($new);
print_r($new);

output

Array
(
    [0] => 2
    [1] => 3
    [2] => 4
    [3] => 10
)

UPDATE

// Array ( [0] => 10 ) Array ( [0] => 2 ) Array ( [0] => 3 ) Array ( [0] => 4 ) Array ( [0] => 5 ) Array ( [0] => 6 ) Array ( [0] => 7 ) Array ( [0] => 8 ) Array ( [0] => 9 ) Array ( [0] => 1 ) 


$mainArray = [
    ["10"], ["2"],["3"], ["4"],
];

function mergeAndSortArrays($arr) {
    $newArr =  array_map(function($e) {
        return (int) $e[0];
    }, $arr);
    sort($newArr);
    return $newArr;
}

output

Array
(
    [0] => 2
    [1] => 3
    [2] => 4
    [3] => 10
)

CodePudding user response:

Here are ways to sort arrays in php

sort() - sort arrays in ascending order
rsort() - sort arrays in descending order
asort() - sort associative arrays in ascending order, according to the value
ksort() - sort associative arrays in ascending order, according to the key
arsort() - sort associative arrays in descending order, according to the value
krsort() - sort associative arrays in descending order, according to the key

Pick one.

$nums = array("10", "2", "5");
sort($nums);
print_r($nums);

//Array ( [0] => 2 [1] => 5 [2] => 10 )
  •  Tags:  
  • php
  • Related