Reputation: 21701
I have array returned
$header_html = array(1=>array('width'=>40,
'sort_case'=>23,
'title'=>'AxA'),
2=>array('width'=>50,
'sort_case'=>7,
'title'=>'B2B'),
3=>array('width'=>100,
'sort_case'=>12,
'title'=>'C12')
);
I want to get new array that depend on $header_array=array('AxA','B2B','C12')
for examples:
if have $header_array=array('C12','B2B','AxA').
the new $header_html will be:
$header_html = array(
1=>array('width'=>100,
'sort_case'=>12,
'title'=>'C12'),
2=>array('width'=>50,
'sort_case'=>7,
'title'=>'B2B'),
3=>array('width'=>40,
'sort_case'=>23,
'title'=>'AxA')
);
and so on...
Anybody know how to do this?
Upvotes: 3
Views: 518
Reputation: 12140
It sounds like you want a function to return the array elements in the order you specify in $header_array
. If so, here's a stab:
function header_resort($header_array, $header_html) {
foreach($header_array as $i => $val) {
foreach($header_html as $obj) {
if( $obj->title == $val )
$header_html_new[$i] = $obj;
}
}
return $header_html_new;
}
Upvotes: 1
Reputation: 562230
You need a user-defined sort so you can access individual fields of the elements to sort:
function mysort($a, $b)
{
global $header_array;
$pos1 = array_search($a["title"], $header_array);
$pos2 = array_search($b["title"], $header_array);
if ($pos1 == $pos2) { return 0; }
return $pos1 < $pos2 ? -1 : 1;
}
$header_array = array("CCC", "BBB", "AAA");
usort($header_html, "mysort");
print_r($header_array);
note: usort()
returns true on success or false on failure; it does not return the resorted array.
Upvotes: 2
Reputation: 5913
In PHP 5.3, you can easily do this with a functor and usort.
class MyComparator {
protected $order = array();
public function __construct() {
$values = func_get_args();
$i = 0;
foreach($values as $v) {
$this->order[$v] = $i;
$i++;
}
}
public function __invoke($a, $b) {
$vala = isset($this->order[$a['title']]) ?
$this->order[$a['title']] : count($this->order);
$valb = isset($this->order[$b['title']]) ?
$this->order[$b['title']] : count($this->order);
if($vala == $valb) return 0;
return $vala < $valb ? -1 : 1;
}
}
You can use it like that:
$sorter = new MyComparator('CCC', 'AAA', 'BBB');
usort($header_html, $sorter);
Upvotes: 2
Reputation: 239230
You can sort the array with a custom comparison function using usort:
function cmp($a, $b) {
// Sort via $a['title'] and $b['title']
}
usort($header_html, 'cmp');
The trick is coming up with a comparison function that does what you want. To simply sort backwards by title, you could use:
function cmp($a, $b) {
if ($a['title'] == $b['title'])
return 0;
// usually return -1 if $a < $b, but we're sorting backwards
return ($a['title'] < $b['title'] ? 1 : -1;
}
Upvotes: 2