Blair McMillan
Blair McMillan

Reputation: 5349

Sorting an array based on the order of a separate array

The code that I have written is based on this similar question, however I'm having trouble working out convert it to work within a class and without the globals use.

Here's what I'm wanting to do.

Suppose I have 2 arrays:

$headings = array(
    'id' => 'ID',
    'name' => 'Name',
);

$rows = array(
    array(
        'id' => 1,
        'name' => 'Jo Blogs',
    ),
    array(
        'name' => 'John Smith',
        'id' => 2,
        'other' => 'Potentially other data'
    ),
);

I would like to sort $rows into the order specified in $headings with any undefined keys appearing at the end. For example, after sorting $rows would look like:

$rows = array(
    array(
        'id' => 1,
        'name' => 'Jo Blogs',
    ),
    array(
        'id' => 2,
        'name' => 'John Smith',
        'other' => 'Potentially other data'
    ),
);

The code which works outside of a class is:

$headings = array(
    'id' => 'ID',
    'name' => 'Name',
);

$rows = array(
    array(
        'id' => 1,
        'name' => 'Jo Blogs',
    ),
    array(
        'name' => 'John Smith',
        'id' => 2,
        'other' => 'Potentially other data'
    ),
);

var_dump($rows);

array_walk($rows, "sort_it");

var_dump($rows);

function sort_it(&$value, $key) {
    uksort($value, "cmp");
}

function cmp($a, $b) {
    global $headings;

    if (!isset($headings[$a]) || !isset($headings[$b]) || $headings[$a]>$headings[$b]){
        return 1;
    }else{
        return -1;
    }

}

And outputs:

array
  0 => 
    array
      'id' => int 1
      'name' => string 'Jo Blogs' (length=8)
  1 => 
    array
      'name' => string 'John Smith' (length=10)
      'id' => int 2
      'other' => string 'Potentially other data' (length=22)
array
  0 => 
    array
      'id' => int 1
      'name' => string 'Jo Blogs' (length=8)
  1 => 
    array
      'id' => int 2
      'name' => string 'John Smith' (length=10)
      'other' => string 'Potentially other data' (length=22)

Which is correct. So again, how do I get rid of the use of the global. I know that array_walk($rows, array($this, "sort_it")); will use $this->sort_it(). Unfortunately this has to work in PHP 5.2.14 (so no fancy fancy from 5.3).

Thanks.

Upvotes: 3

Views: 188

Answers (1)

ahmetunal
ahmetunal

Reputation: 3950

$result = fix_array_order($rows, $headings);
print_r($result);

function fix_array_order($array, $order_array)
{
    $order = array_keys($order_array);

    $result = array();
    foreach($array as $arr)
    {
        $new_sub_array = array();
        foreach($order as $key)
        {
            $new_sub_array[$key] = $arr[$key];
        }

        $diff = array_diff(array_keys($arr), $order);
        foreach($diff as $diff_key)
        {
        $new_sub_array[$diff_key] = $arr[$key];
        }
        $result[] = $new_sub_array;
    }
    return $result;
}

Upvotes: 2

Related Questions