Showing posts with label PHP SORT Array. Show all posts
Showing posts with label PHP SORT Array. Show all posts

Monday, 3 September 2018

PHP Sort array with additional matrix exceptions

I have for example two arrays:

One with exceptions:
array('dog', 'cat', 'macbook')

And another with all values:
array('computer', 'mom', 'cat', 'dog')

I would like to get sorted array with following order:
array('dog', 'cat', 'computer', 'mom') // first with exception order and another elements alphabetically

How to do it?

Here is my code
$exceptions =       array('dog', 'cat', 'macbook');
$main_arr =         array('computer', 'mom', 'cat', 'dog');
$temp = [];
$result_arr = [];
foreach($exceptions as $k => $v){
    if(in_array($v, $main_arr)){
        $result_arr[] = $v; // adding in result array which matches exceptions with main array
        unset($main_arr[array_search($v,$main_arr)]); // unsetting from main array with matches with exception array
    }
}
$main_arr = array_values(array_filter($main_arr)); // correcting indexing of main array

$result_arr = array_merge($result_arr, $main_arr);
print_r($result_arr);

You can write your custom code like this, anyway this code will work

PHP - Sorting Tables

So I am wanting to sort an array depending on what the user selects, I have managed to get it all working (With a little help from you guys) and now I am trying to clean up the code. This is what i've got

//Global Sorting Functions (For Rows to Columns)
//Function to sort up or down
function cmpdwn($a, $b) {
    return strcasecmp($a["Name"], $b["Name"]);
}

function cmpup($a, $b, $c) {
    return strcasecmp($b[$c], $a[$c]);
}

//Name Ordering Function ---------------------------------
function nameorder($data) {
    //If Up sorts Assending if Down Decending
    if ($_POST['Sortby'] == "NameDown") {
        uasort($data, "cmpdwn");
    } else {
        uasort($data, "cmpup");
    }

    $nameorder = array();
    $count = 0;
    while (list($key, $value) = each($data)) {
        $nameorder[$count] = $key;
        $count++;
    }
    return $nameorder;
}

This creates an array for an order to print the data in name order, I will be repeating this for email too and others. What i wanted to do is re-use the "cmp" function by putting more than $a and $b into (i.e. $c = "Name" then i can put in "Email" or what ever // cmpup as example). But to from the little i know is that this function is declaring an argument for uasort and i don't send variables into it. Is there a way to do so or is it a case of re writing the function repeatedly
Thanks And Big Love

Try to make object
class MyComparator {

    private $key;

    function __construct($key) {
        $this->key = $key;
    }

    function compare($a, $b) {
        return strcasecmp($b[$this->key], $a[$this->key]);
    }

    public function setKey($key) {
        $this->key = $key;
    }
}

And use it
$compararor = new MyComparator("Name");

usort($data, array($compararor, "compare"));

OR in php >= 5.3.0. you can use __invoke() method
class MyComparator {

    private $key;

    function __construct($key) {
        $this->key = $key;
    }

    function __invoke($a, $b) {
        return strcasecmp($b[$this->key], $a[$this->key]);
    }

    public function setKey($key) {
        $this->key = $key;
    }
}

And simple call it with
$compararor = new MyComparator("Name");

usort($data, $compararor);

PHP sorting table

This question already has an answer here:

  • How can I sort arrays and data in PHP? 7 answers
Simple functions like PHP_SORT doesn't work, also tips from comments couldn't help me enough. I'm trying to sort my table by int values but I can't manage it. This is sample of my table.
array(3) {
 ["normal"]=>
 array(20) {
[58]=>
int(7343)
[33]=>
int(7032)
[34]=>
int(7322)
[65]=>
int(7017)
[60]=>
int(6996)
[62]=>
int(7022)
[35]=>
int(6508)
[56]=>
int(7323)
[61]=>
int(413)
[57]=>
int(7327)
[67]=>
int(7001)
[72]=>
int(6469)
[64]=>
int(5297)
[59]=>
int(5135)
[71]=>
int(5322)
[70]=>
int(5452)
[69]=>
int(6556)
[68]=>
int(6436)
[66]=>
int(6840)
[48]=>
int(6862)
 }
 ["high"]=>
array(19) {
[58]=>
int(2717)
[60]=>
int(2562)
[33]=>
int(2718)
[34]=>
int(2722)
[61]=>
int(1964)
[64]=>
int(2337)
[65]=>
int(368)
[67]=>
int(2308)
[72]=>
int(1880)
[59]=>
int(2202)
[57]=>
int(2587)
[56]=>
int(1474)
[62]=>
int(2416)
[48]=>
int(2455)
[35]=>
int(2356)
[69]=>
int(1910)
[71]=>
int(2229)
[68]=>
int(2293)
[63]=>
int(2582)
 }
  ["low"]=>
 array(12) {
[58]=>
int(1905)
[48]=>
int(1771)
[60]=>
int(1842)
[56]=>
int(1179)
[57]=>
int(1714)
[64]=>
int(1243)
[34]=>
int(1903)
[63]=>
int(57)
[59]=>
int(1837)
[35]=>
int(1725)
[62]=>
int(1594)
[33]=>
int(1858)
 }
}

Please give me some tips. I will be very pleased.
SOLUTION:
$newArray = array();
foreach($morning_code as $k=>$subArray){
   arsort($subArray);
   $newArray[$k] = $subArray;
}
var_dump($newArray);


if you want to value sort use below
$sortingen = array("normal"=> array(58=>7343,33=>23424,
newArray = Array();

foreach($sortingen as $k=>$subArray){
    sort($subArray);
    newArray[$k] = $subArray;
}

if you want to key sort use below
$sortingen = array("normal"=> array(58=>7343,33=>23424,
newArray = Array();

foreach($sortingen as $k=>$subArray){
    ksort($subArray);
    newArray[$k] = $subArray;
}

PHP sort table (loading database values) from the shortest to the longest

I have next code:

<select>
    <?php foreach ($values as $info) { ?>
      <option value="<?php echo $info['id'] ?>" <?php echo $value == $info['id'] ? 'selected="selected"' : '' ?>><?php echo $info['text'] ?></option>
    <?php } ?>
  </select>

i loading values from database! And have next results:
    <option value="1">Jacksonville (Florida)</option>
    <option value="2">Florida reg.</option>
    <option value="3">Florentia</option>
    <option value="9999">Florida</option>
    <option value="5">Miami (Florida)</option>

how to do: on the top were the shortest results for 'text':
Florida
Florentia
Florida reg.
Miami (Florida)
Jacksonville (Florida)
        <option value="9999">Florida</option>
        <option value="3">Florentia</option>
        <option value="2">Florida reg.</option>
        <option value="5">Miami (Florida)</option>
        <option value="1">Jacksonville (Florida)</option>

Thanks

You can use usort, as answered here in another question.
function sort($a,$b){
    return strlen($b)-strlen($a);
}

usort($array,'sort');

PHP: Sort the table by value of occurrences in the text?

I need to order an unknown array of keywords by the order they occur in a text string.

// random order of unknown values
$keywords = array( "orange", "green apple", "banana" );

// ordered occurrences
$text = "This is text where the keywords can appear as well like green apple trees.
Then follows text where the keywords are in order and surrounded by unique syntax.

((randomly ordered keywords))
((foo))
((banana))
((orange))
((baz))
((green apple))
((baz))
";

// reorder keywords
// maybe preg_match( "/.+\({2}(".$keywordItem.")\).*/", $text, $matches )
// ...

// Order should be banana, orange, green apple
print_r( $keywords );

The solution may include ´preg_match`, but I don't know where to start.

  1. First extract the words from the string (I'm assuming each keyword appears in the text in it's own separate line)
    preg_match_all('/[ \t]*\(\((.*)\)\)[ \t]*/', $text, $matches);`
    
    
  2. Then you take the produced array and intersect with the keywords
    if (isset($matches[1])) {
      $results = array_intersect($matches[1], $keywords);
    }
    
    
Here's the complete snippet (php pad):
$keywords = array( "orange", "green apple", "banana" );

$text = "This is text where the keywords can appear as well like green apple trees.
The follows text where the keywords are in order and surrounded by unique syntax.

((randomly ordered keywords))
((foo))
((banana))
((orange))
((baz))
((green apple))
((baz))
";

// extract keywords
$matches = array();
$results = array();
preg_match_all('/[ \t]*\(\((.*)\)\)[ \t]*/', $text, $matches);

// Sort keywords
if (isset($matches[1])) {
  $results = array_intersect($matches[1], $keywords);
}

var_dump($results);

Friday, 31 August 2018

Sort the multidimensional array from top to bottom in PHP

I have checked on here and cant find a similar result so if this has been asked I do apologies.

Anyway, I am generating an multi array which has been generated by a nice little class.
Anyway the array comes like this when output:
array(2047) {
    [0]=> array(6) {
        ["name"]=> string(4) "name"
        ["gamesplayed"] => string(2) "26"
        ["points"] => string(2) "26"
    }
    [1]=> array(6) {
        ["name"]=> string(4) "name"
        ["gamesplayed"] => string(2) "26"
        ["points"] => string(2) "42"
    }
    [2]=> array(6) {
        ["name"]=> string(4) "name"
        ["gamesplayed"] => string(2) "26"
        ["points"] => string(2) "16"
    }
    // and so on
}

My question is... Is there an easy php function or a neat way on sorting the array into high to low using the points value?
I have had a look at a few php functions but they are just for standard arrays with a single value.
Thanks for any help given :)
UPDATE
I have tried this and it does not sort by points.
Here is the class I am doing it with:
//create sort value
private function sorting_table($a, $b){
    return $a['points'] - $b['points'];
}

//sort all users into a table and order the highest to the lowest
public function output_prediction_table($pdo, $year){

    //get all uers and put in an array with games played and points.
    $getallusers = $pdo->prepare("SELECT userid FROM userpredictions WHERE year=:year");
    $getallusers->execute(array(':year' => $year));

    //create the multidimentional array
    $multidimentional_array = array();

    while($fetchallusers = $getallusers->fetch()){

        $multidimentional_array[] = array(
            'name' => $this->get_username($pdo, $fetchallusers['userid']),
            'games' => $this->get_games_played($pdo, $year),
            'points' => $this->make_points($pdo, $year, $fetchallusers['userid']),
            'userid' => $fetchallusers['userid']
        );

    }

    usort($multidimentional_array, array($this, 'sorting_table'));

    $output = '<table class="table-striped">';
    $output .= '<tr class="t-h"><td class="t-c">Position</td><td>Username</td><td>Games Played</td><td>Points</td></tr>';
    $tablenumber = 1;

    foreach($multidimentional_array as $newarray){

        $output .= '<tr><td class="t-c">'.$tablenumber.'</td><td><a href="/user/'.$this->sluggify($newarray["name"]).'/'.$newarray["userid"].'/" title="View '.ucwords($newarray["name"]).' Profile">'.ucwords($newarray["name"]).'</a></td><td>'.$newarray["games"].'</td><td>'.$newarray["points"].'</td></tr>';
        $tablenumber++;

    }

    $output .= '</table>';

    return $output;

}

I am not getting any errors, its just not sorting with the highest points first to the lowest points last.

Try usort
You can do something like this:
usort($array, 'sortByPoints');

function sortByOrder($a, $b) {
    return $a['points'] - $b['points'];
}

Yo can find more examples here: Sort Multi-dimensional Array by Value

Thursday, 30 August 2018

PHP Sort an associative array with a custom order

This question already has an answer here:

  • How can I sort arrays and data in PHP? 7 answers
How can we sort an associative array with custom order? My array look like this
Array
(
    [pa_color] => Array
        (
            [name] => pa_color
            [value] =>
            [position] => 0
            [is_visible] => 1
            [is_variation] => 1
            [is_taxonomy] => 1
        )

    [pa_dimension] => Array
        (
            [name] => pa_dimension
            [value] =>
            [position] => 1
            [is_visible] => 1
            [is_variation] => 0
            [is_taxonomy] => 1
        )

    [pa_travel-duration] => Array
        (
            [name] => pa_travel-duration
            [value] =>
            [position] => 2
            [is_visible] => 1
            [is_variation] => 0
            [is_taxonomy] => 1
        )

    [pa_travel-type] => Array
        (
            [name] => pa_travel-type
            [value] =>
            [position] => 3
            [is_visible] => 1
            [is_variation] => 0
            [is_taxonomy] => 1
        )

    [pa_travelling-with] => Array
        (
            [name] => pa_travelling-with
            [value] =>
            [position] => 4
            [is_visible] => 1
            [is_variation] => 0
            [is_taxonomy] => 1
        )

    [pa_volume] => Array
        (
            [name] => pa_volume
            [value] =>
            [position] => 5
            [is_visible] => 1
            [is_variation] => 0
            [is_taxonomy] => 1
        )

    [pa_weight] => Array
        (
            [name] => pa_weight
            [value] =>
            [position] => 6
            [is_visible] => 1
            [is_variation] => 0
            [is_taxonomy] => 1
        )

)

and i want this array is like pa_travel-duration first pa_volume second ?? I know there is a native php function usort but i could not understand this.

This will do the work, but im pretty sure there's much better ways to do it:
Code:
$array = array("pa_color" => "color",
              "pa_dimension" => "dimension",
              "pa_travel-duration" => "Random Stuff: " . rand(100,999),
              "pa_volume" => "volumen"
              );
$tmp = array("pa_travel-duration" =>  $array["pa_travel-duration"],
            "pa_volume" =>  $array["pa_volume"],
);

unset($array["pa_travel-duration"], $array["pa_volume"]);
$array = array_merge($tmp,$array);

print_r($array);

Result:
Array
(
    [pa_travel-duration] => Random Stuff: 127
    [pa_volume] => volumen
    [pa_color] => color
    [pa_dimension] => dimension
)

Take care because if the array doesn't have the proper key it will throw an error, you need to add few checks there.

PHP How to sort the associative array first by the keys then by the values?

$arr =array(
    28 => 23,
    26 => 23,
    15 => 12,
    29 => 12,
    1 => 12,
    16 => 15,
    30 => 15,
    11 => 12,
    8 => 23,
    33 => 23
);

how to sort like this :
8 => 23
26 => 23
28 => 23
33 => 23
16 => 15
30 => 15
1 => 12
11 => 12
15 => 12
29 => 12


Use uksort, but make the array available to the comparison function for the secondary comparison by value. Making it a global variable would be the quickest + dirtiest way.

PHP: Sort set based on another table


 I have visited similar question here but not getting what i want in php. Suppose i have 2 arrays. All checking should be case insensitive. say Field0 is same as field0 or fiEld1 is same as Field1.


array1 is array(
"0"=>"field0",
"1"=>"field1",
"2"=>"field2",
"3"=>"field3",
);

array2 is array(
"0"=>"field3",
"1"=>"field2",
"2"=>"field0",
"3"=>"field1",
"4"=>"field6",
"5"=>"field5",
);

Now I want array2 to be sorted based on array1 like the following:
array2 is array(
"0"=>"field0",
"1"=>"field1",
"2"=>"field2",
"3"=>"field3",
"4"=>"field6",
"5"=>"field5",
);

look here array1 has 4 elements so array2 should be sorted based exactly 4 elements of array1 and rest 2 element (index 4,5 of array2) should as it is in array2 before.

Try array_intersect combined with array_diff:
<?php
$array1 = array(
    "0"=>"field0",
    "1"=>"field1",
    "2"=>"field2",
    "3"=>"field3",
);

$array2 = array(
    "0"=>"field3",
    "1"=>"field2",
    "2"=>"field0",
    "3"=>"field1",
    "4"=>"field6",
    "5"=>"field5",
);

$array3 = array_merge(
    array_intersect($array1, $array2),
    array_diff($array2, $array1)
);

var_dump($array3);

Update
For a case insensitive approach, use array_map to guarantee all entries in both arrays are lower-cased:
$array3 = array_map('strtolower', $array1);
$array4 = array_map('strtolower', $array2);

$array5 = array_merge(
    array_intersect($array3, $array4),
    array_diff($array4, $array3)
);

var_dump($array5);

PHP sort array with date as key with date format


This question already has an answer here:


  • How to sort a date array in PHP 4 answers
I have an array as follow: The first key element is a date with the format dd-mm-yyyy
Array
(
    [08-12-2015] => Array
        (
          ------------
        )
    [07-12-2015] => Array
        (
          ------------
        )
    [09-12-2015] => Array
        (
          ------------
        )
)

Is it possible to sort this array on the first key value bij date? So the first element is
Array
(
    [07-12-2015] => Array
        (
          ------------
        )
    [08-12-2015] => Array
        (
          ------------
        )
    [09-12-2015] => Array
        (
          ------------
        )
)


Yes, I found the solution:
function order_date($a1,$b1) {
    $format = 'd-m-Y';
    $a = strtotime(date_format(DateTime::createFromFormat($format, $a1), 'Y-m-d H:i:s'));
    $b = strtotime(date_format(DateTime::createFromFormat($format, $b1), 'Y-m-d H:i:s'));
    if ($a == $b)
    {
        return 0;
    }
    else if ($a > $b)
    {
        return 1;
    }
    else {
        return -1;
    }
}

uksort($array, "order_date");

PHP Sort Array By SubArray Value by 3rd level but with clues


I'm totally desperate.


How can I sort an array in 3rd level that has an ID in the second level?
I want to sort this array only for "cars" and then ascending by "age"
array (
    ['cars'] => array (
        [23] => array(
            ['age'] => 10,
            ['color'] => 'yellow',
        ),
        [16] => array(
            ['age'] => 12,
            ['color'] => 'purple'
        ),
        [45] => array(
            ['age'] => 3,
            ['color'] => 'silver'
        )
    ),
    ['pages'] => array (
        [0] => array (
            ['number'] => 2
        )
    )
)


You can use uasort.
uasort($a['cars'], function($a, $b) {
   return $a['age'] > $b['age'] ? 1 : -1;
});


PHP sort array by the number of elements?


I have a multi-dimension array of australian states, and inside each state there are items. I was wondering if it were possible to reorder an array so the states with the most amount of items are displayed first?


Here's my array, any help would be appreciated :)
[ACT] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 14
                    [name] => Burning Log Megastore
                    [state] => ACT
                    [classid] => 1
                )

            [1] => stdClass Object
                (
                    [id] => 21
                    [name] => Fyshwick Home & Heating
                    [state] => ACT
                    [classid] => 1
                )

        )

    [NSW] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 36
                    [name] => A1 Hot Wood
                    [state] => NSW
                    [classid] => 11
                )

            [1] => stdClass Object
                (
                    [id] => 40
                    [name] => Abbey Fireplaces
                    [state] => NSW
                    [classid] => 1
                )

            [2] => stdClass Object
                (
                    [id] => 55
                    [name] => Almighty Firewood
                    [state] => NSW
                    [classid] => 11
                )

            [3] => stdClass Object
                (
                    [id] => 70
                    [name] => Aussie Tree Services
                    [state] => NSW
                    [classid] => 11
                )

            [4] => stdClass Object
                (
                    [id] => 75
                    [name] => B C Sands
                    [state] => NSW
                    [classid] => 11
                )

            [5] => stdClass Object
                (
                    [id] => 76
                    [name] => B C Sands
                    [state] => NSW
                    [classid] => 11
                )

            [6] => stdClass Object
                (
                    [id] => 77
                    [name] => B C Sands Mascot
                    [state] => NSW
                    [classid] => 11
                )

            [7] => stdClass Object
                (
                    [id] => 113
                    [name] => Barbeques Galore (Maitland)
                    [state] => NSW
                    [classid] => 1
                )

            [8] => stdClass Object
                (
                    [id] => 114
                    [name] => Barbeques Galore Batemans Bay
                    [state] => NSW
                    [classid] => 1
                )

            [9] => stdClass Object
                (
                    [id] => 116
                    [name] => Barbeques Galore Wagga Wagga
                    [state] => NSW
                    [classid] => 1
                )

            [10] => stdClass Object
                (
                    [id] => 131
                    [name] => Best Burning Fire Fuels
                    [state] => NSW
                    [classid] => 11
                )

            [11] => stdClass Object
                (
                    [id] => 132
                    [name] => Betta Burn Firewood
                    [state] => NSW
                    [classid] => 11
                )

            [12] => stdClass Object
                (
                    [id] => 136
                    [name] => Black Forest Firewood
                    [state] => NSW
                    [classid] => 11
                )

            [13] => stdClass Object
                (
                    [id] => 181
                    [name] => Central Coast Brick Supplies Pty Ltd
                    [state] => NSW
                    [classid] => 1
                )

            [14] => stdClass Object
                (
                    [id] => 188
                    [name] => Cheminee Pty Ltd
                    [state] => NSW
                    [classid] => 1
                )

            [15] => stdClass Object
                (
                    [id] => 249
                    [name] => Embers Heating & Restoration Supplies
                    [state] => NSW
                    [classid] => 1
                )

            [16] => stdClass Object
                (
                    [id] => 250
                    [name] => Emmbers Firewood Supplies
                    [state] => NSW
                    [classid] => 11
                )

            [17] => stdClass Object
                (
                    [id] => 292
                    [name] => Goulburn Sand & Soil
                    [state] => NSW
                    [classid] => 11
                )

            [18] => stdClass Object
                (
                    [id] => 304
                    [name] => Gunida Gunyah Aboriginal Corporation
                    [state] => NSW
                    [classid] => 11
                )

            [19] => stdClass Object
                (
                    [id] => 334
                    [name] => J  Perram Firewood Supplies
                    [state] => NSW
                    [classid] => 11
                )

            [20] => stdClass Object
                (
                    [id] => 346
                    [name] => Jetmaster (Aust) Pty Ltd
                    [state] => NSW
                    [classid] => 1
                )

            [21] => stdClass Object
                (
                    [id] => 402
                    [name] => Mark H Newton
                    [state] => NSW
                    [classid] => 4
                )

            [22] => stdClass Object
                (
                    [id] => 416
                    [name] => Might Burn Red Gum Pty Ltd
                    [state] => NSW
                    [classid] => 11
                )

            [23] => stdClass Object
                (
                    [id] => 430
                    [name] => Mr Stoves Pool World
                    [state] => NSW
                    [classid] => 1
                )

            [24] => stdClass Object
                (
                    [id] => 455
                    [name] => O'Brien's Redgum Sawmills
                    [state] => NSW
                    [classid] => 11
                )

            [25] => stdClass Object
                (
                    [id] => 477
                    [name] => PJ & CM Ducat
                    [state] => NSW
                    [classid] => 11
                )

            [26] => stdClass Object
                (
                    [id] => 483
                    [name] => Quality Firewood All Seasons
                    [state] => NSW
                    [classid] => 11
                )

            [27] => stdClass Object
                (
                    [id] => 487
                    [name] => R J & M E Grealy
                    [state] => NSW
                    [classid] => 11
                )

            [28] => stdClass Object
                (
                    [id] => 494
                    [name] => RN & CA Taylor
                    [state] => NSW
                    [classid] => 11
                )

            [29] => stdClass Object
                (
                    [id] => 500
                    [name] => Rouse Hill Firewood
                    [state] => NSW
                    [classid] => 11
                )

            [30] => stdClass Object
                (
                    [id] => 504
                    [name] => Sapphire Coast Firewood
                    [state] => NSW
                    [classid] => 11
                )

            [31] => stdClass Object
                (
                    [id] => 534
                    [name] => Sydney Heaters Pty Ltd
                    [state] => NSW
                    [classid] => 1
                )

            [32] => stdClass Object
                (
                    [id] => 551
                    [name] => The Woodyard
                    [state] => NSW
                    [classid] => 11
                )

            [33] => stdClass Object
                (
                    [id] => 576
                    [name] => W R Campi
                    [state] => NSW
                    [classid] => 11
                )

            [34] => stdClass Object
                (
                    [id] => 602
                    [name] => Wood 4 U
                    [state] => NSW
                    [classid] => 11
                )

            [35] => stdClass Object
                (
                    [id] => 603
                    [name] => Wood Galore
                    [state] => NSW
                    [classid] => 11
                )

            [36] => stdClass Object
                (
                    [id] => 604
                    [name] => Wood Galore
                    [state] => NSW
                    [classid] => 11
                )

        )

    [QLD] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 665
                    [name] => Brightspark Firewood Supplies
                    [state] => QLD
                    [classid] => 11
                )

            [1] => stdClass Object
                (
                    [id] => 702
                    [name] => Gleno's Firewood
                    [state] => QLD
                    [classid] => 11
                )

            [2] => stdClass Object
                (
                    [id] => 704
                    [name] => Gold Coast Fireplace & Barbeque Centre
                    [state] => QLD
                    [classid] => 1
                )

            [3] => stdClass Object
                (
                    [id] => 732
                    [name] => Longburn Wood
                    [state] => QLD
                    [classid] => 11
                )

            [4] => stdClass Object
                (
                    [id] => 742
                    [name] => Out In The Styx
                    [state] => QLD
                    [classid] => 11
                )

            [5] => stdClass Object
                (
                    [id] => 746
                    [name] => Quickfire Firewood
                    [state] => QLD
                    [classid] => 11
                )

        )

    [SA] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 786
                    [name] => Adelaide Wholesale Landscape Supplies
                    [state] => SA
                    [classid] => 11
                )

            [1] => stdClass Object
                (
                    [id] => 825
                    [name] => Clare Wood Yard
                    [state] => SA
                    [classid] => 11
                )

            [2] => stdClass Object
                (
                    [id] => 826
                    [name] => Clewers Electrical and Furniture
                    [state] => SA
                    [classid] => 1
                )

            [3] => stdClass Object
                (
                    [id] => 832
                    [name] => Cullen Transport & Firewood Supplies
                    [state] => SA
                    [classid] => 11
                )

            [4] => stdClass Object
                (
                    [id] => 852
                    [name] => Enviro Systems Renewable Resources Ltd.
                    [state] => SA
                    [classid] => 11
                )

            [5] => stdClass Object
                (
                    [id] => 867
                    [name] => Gawler Landscaping Supplies
                    [state] => SA
                    [classid] => 11
                )

            [6] => stdClass Object
                (
                    [id] => 871
                    [name] => Green Hornet Building & Landscape Supplies
                    [state] => SA
                    [classid] => 11
                )

            [7] => stdClass Object
                (
                    [id] => 899
                    [name] => Mexican Living
                    [state] => SA
                    [classid] => 1
                )

            [8] => stdClass Object
                (
                    [id] => 903
                    [name] => Mount Barker Landscape Centre
                    [state] => SA
                    [classid] => 11
                )

            [9] => stdClass Object
                (
                    [id] => 911
                    [name] => Pecan Engineering Pty Ltd
                    [state] => SA
                    [classid] => 1
                )

            [10] => stdClass Object
                (
                    [id] => 919
                    [name] => PW & JD Plunkett
                    [state] => SA
                    [classid] => 11
                )

            [11] => stdClass Object
                (
                    [id] => 922
                    [name] => Renmark Firewoods & Storage Services
                    [state] => SA
                    [classid] => 11
                )

            [12] => stdClass Object
                (
                    [id] => 930
                    [name] => South Coast Firewood (FWS Inc)
                    [state] => SA
                    [classid] => 11
                )

            [13] => stdClass Object
                (
                    [id] => 937
                    [name] => Tinpak Trading Pty Ltd
                    [state] => SA
                    [classid] => 11
                )

            [14] => stdClass Object
                (
                    [id] => 940
                    [name] => Traeger's Earthmoving & Transport
                    [state] => SA
                    [classid] => 11
                )

            [15] => stdClass Object
                (
                    [id] => 947
                    [name] => Waterways Farm
                    [state] => SA
                    [classid] => 11
                )

        )

    [TAS] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 985
                    [name] => Eastern Tiers Firewood
                    [state] => TAS
                    [classid] => 11
                )

            [1] => stdClass Object
                (
                    [id] => 998
                    [name] => Goods Water & Garden Supplies
                    [state] => TAS
                    [classid] => 11
                )

            [2] => stdClass Object
                (
                    [id] => 1011
                    [name] => K-Mac Wood Supplies
                    [state] => TAS
                    [classid] => 11
                )

            [3] => stdClass Object
                (
                    [id] => 1019
                    [name] => Leslie Vale Landscape & Gravel Supplies
                    [state] => TAS
                    [classid] => 11
                )

            [4] => stdClass Object
                (
                    [id] => 1023
                    [name] => Newmans Heating Shop
                    [state] => TAS
                    [classid] => 1
                )

            [5] => stdClass Object
                (
                    [id] => 1029
                    [name] => Pellet Fires Tasmania
                    [state] => TAS
                    [classid] => 1
                )

        )

    [VIC] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 561
                    [name] => TRT Pastoral Group
                    [state] => VIC
                    [classid] => 11
                )

            [1] => stdClass Object
                (
                    [id] => 1059
                    [name] => A Grade Garden Products
                    [state] => VIC
                    [classid] => 11
                )

            [2] => stdClass Object
                (
                    [id] => 1062
                    [name] => A.F. Gason Pty Ltd
                    [state] => VIC
                    [classid] => 1
                )

            [3] => stdClass Object
                (
                    [id] => 1088
                    [name] => Alpine Timber
                    [state] => VIC
                    [classid] => 11
                )

            [4] => stdClass Object
                (
                    [id] => 1093
                    [name] => Aranbe Heat
                    [state] => VIC
                    [classid] => 1
                )

            [5] => stdClass Object
                (
                    [id] => 1096
                    [name] => ASAP Firewood
                    [state] => VIC
                    [classid] => 11
                )

            [6] => stdClass Object
                (
                    [id] => 1105
                    [name] => Bairnsdale Stoves Heaters & BBQ's
                    [state] => VIC
                    [classid] => 1
                )

            [7] => stdClass Object
                (
                    [id] => 1176
                    [name] => Burra Garden Supplies
                    [state] => VIC
                    [classid] => 11
                )

            [8] => stdClass Object
                (
                    [id] => 1231
                    [name] => Daryl Fagan Firewood
                    [state] => VIC
                    [classid] => 11
                )

            [9] => stdClass Object
                (
                    [id] => 1273
                    [name] => Firefox Industries Pty Ltd
                    [state] => VIC
                    [classid] => 1
                )

            [10] => stdClass Object
                (
                    [id] => 1297
                    [name] => Geoffrey R Gelletly
                    [state] => VIC
                    [classid] => 4
                )

            [11] => stdClass Object
                (
                    [id] => 1301
                    [name] => Gippsland Wood Heater Repairs
                    [state] => VIC
                    [classid] => 1
                )

            [12] => stdClass Object
                (
                    [id] => 1303
                    [name] => Glen Dimplex Australia Pty Ltd
                    [state] => VIC
                    [classid] => 1
                )

            [13] => stdClass Object
                (
                    [id] => 1306
                    [name] => Glowin' Firewood
                    [state] => VIC
                    [classid] => 11
                )

            [14] => stdClass Object
                (
                    [id] => 1328
                    [name] => HRL Technology Pty Ltd
                    [state] => VIC
                    [classid] => 1
                )

            [15] => stdClass Object
                (
                    [id] => 1415
                    [name] => Moran Logging Co Pty Ltd
                    [state] => VIC
                    [classid] => 11
                )

            [16] => stdClass Object
                (
                    [id] => 1427
                    [name] => Murray Industries Kerang
                    [state] => VIC
                    [classid] => 11
                )

            [17] => stdClass Object
                (
                    [id] => 1428
                    [name] => Murray Industries Swan Hill
                    [state] => VIC
                    [classid] => 4
                )

            [18] => stdClass Object
                (
                    [id] => 1436
                    [name] => North East Fwd Strategy Implementn Comm
                    [state] => VIC
                    [classid] => 1
                )

            [19] => stdClass Object
                (
                    [id] => 1438
                    [name] => Northern Landscape Supplies
                    [state] => VIC
                    [classid] => 11
                )

            [20] => stdClass Object
                (
                    [id] => 1448
                    [name] => Park Orchards Garden & Building Supplies
                    [state] => VIC
                    [classid] => 11
                )

            [21] => stdClass Object
                (
                    [id] => 1476
                    [name] => Redgumdave
                    [state] => VIC
                    [classid] => 11
                )

            [22] => stdClass Object
                (
                    [id] => 1493
                    [name] => Sand, Soil & Rocks Pty Ltd
                    [state] => VIC
                    [classid] => 11
                )

            [23] => stdClass Object
                (
                    [id] => 1495
                    [name] => Shamic Sheetmetal Aust  Pty Ltd
                    [state] => VIC
                    [classid] => 1
                )

            [24] => stdClass Object
                (
                    [id] => 1516
                    [name] => Surrey Hills Firewood Supplies
                    [state] => VIC
                    [classid] => 11
                )

            [25] => stdClass Object
                (
                    [id] => 1529
                    [name] => The Flue Factory Pty Ltd
                    [state] => VIC
                    [classid] => 1
                )

            [26] => stdClass Object
                (
                    [id] => 1553
                    [name] => Trevor King
                    [state] => VIC
                    [classid] => 11
                )

            [27] => stdClass Object
                (
                    [id] => 1585
                    [name] => Whitlands Engineering
                    [state] => VIC
                    [classid] => 1
                )

            [28] => stdClass Object
                (
                    [id] => 1591
                    [name] => Wignells of Melbourne Pty Ltd
                    [state] => VIC
                    [classid] => 1
                )

            [29] => stdClass Object
                (
                    [id] => 1604
                    [name] => WWF Australia
                    [state] => VIC
                    [classid] => 1
                )

            [30] => stdClass Object
                (
                    [id] => 1609
                    [name] => Yarra Timber Salvage
                    [state] => VIC
                    [classid] => 11
                )

        )

    [WA] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 1623
                    [name] => All Suburbs Garden & Wood Supply
                    [state] => WA
                    [classid] => 11
                )

            [1] => stdClass Object
                (
                    [id] => 1628
                    [name] => Barbecue Bazaar Cannington
                    [state] => WA
                    [classid] => 1
                )

            [2] => stdClass Object
                (
                    [id] => 1672
                    [name] => European Wood Fired Ovens
                    [state] => WA
                    [classid] => 1
                )

            [3] => stdClass Object
                (
                    [id] => 1681
                    [name] => Freo Firewood Supply
                    [state] => WA
                    [classid] => 11
                )

            [4] => stdClass Object
                (
                    [id] => 1740
                    [name] => Roleystone Firewood
                    [state] => WA
                    [classid] => 11
                )

            [5] => stdClass Object
                (
                    [id] => 1747
                    [name] => Smart Burn Pty Ltd
                    [state] => WA
                    [classid] => 1
                )

            [6] => stdClass Object
                (
                    [id] => 1748
                    [name] => Specialised Tree Service
                    [state] => WA
                    [classid] => 11
                )

            [7] => stdClass Object
                (
                    [id] => 1855
                    [name] => York Firewood & Milling
                    [state] => WA
                    [classid] => 11
                )

        )

)


After running this, $arr will now be sorted from highest populated elements to lower.
function cmpArray($a, $b)
{
    $countA = count($a);
    $countB = count($b);
    if ($countA == $countB) {
        return 0;
    }
    return ($countA < $countB) ? 1 : -1;
}

uasort($arr, "cmpArray");

Wednesday, 29 August 2018

PHP: Sort a multidimensional array, but keep its substructure

I have a multidimensional arrays with the following structure:

$arr[0][0] = 1.24;
$arr[0][1] = 5.21;
$arr[0][2] = 2.72;
$arr[0][3] = 1.89;
$arr[0][4] = 4.62;

$arr[1][0] = 3.45;
$arr[1][1] = 5.61;
$arr[1][2] = 2.62;
$arr[1][3] = 1.12;
$arr[1][4] = 1.35;

This array should get sorted while keeping the suborder of $arr[0] and $arr[1], so the result looks like this:
$arr[0][0] = 1.24;
$arr[1][0] = 3.45;
$arr[0][1] = 5.21;
$arr[0][2] = 2.72;
$arr[0][3] = 1.89;
$arr[0][4] = 4.62;
$arr[1][2] = 2.62;
$arr[1][3] = 1.12;
$arr[1][4] = 1.35;
$arr[1][1] = 5.61;

I do not care in which form the result get saved, but I need both keys and the value. Hope you understand and can help me.

How about looping the outer array and sorting the inner?
foreach ($arr as $id => $data) {
 sort($data);
 $arr[$id] = $data;
}

PHP: sorting a multidimensional array by an attribute

I've got a multi dimensional array as seen below. I want to sort the 2nd level arrays based the [date] attribute. I believe I can use array_multisort, but I'm unsure of how to proceed.

My array is in the variable $presentations
Array
(
    [0] => Array
        (
            [date] => 20111104
            [name] => Name of Presentation
        )

    [1] => Array
        (
            [date] => 20111118
            [name] => sadf
        )

    [2] => Array
        (
            [date] => 20100427
            [name] => older one
        )

    [3] => Array
        (
            [date] => 20101213
            [name] => Another one from 2010
        )

    [4] => Array
        (
            [date] => 20110719
            [name] => sdf
        )

    [5] => Array
        (
            [date] => 20110614
            [name] => Sixth one
        )

)


usort callback should return 3 types of values, depending on the circumstances:
  • A negative number if parameter $a is less than $b
  • A positive number if parameter $b is less than $a
  • Zero if both $a and $b are equal
usort($presentations, function($a, $b)
{
    if($a['date'] == $b['date'])
    {
        return 0;
    }
    return $a['date'] < $b['date'] ? -1 : 1;
});