Reputation: 4517
I have 2 arrays, 1 holds the data to be displayed and the other holds the order.
the following array will be used in a foreach loop to display:
array(
[Posts] =>
[0] =>
id => 7
content => 'some content'
[1] =>
id => 3,
content => 'some other content'
[2] =>
id => 4,
content => 'some more content'
[3] =>
id => 2,
content => 'some irrelevant content'
)
This array contains the sort positions:
array(
2, 4, 7, 3
)
I would like to sort the first array based on the vaulue in the associative array where the key is id that matches the second array.
Expected output:
array(
[Posts] =>
[0] =>
id => 2,
content => 'some irrelevant content'
[1] =>
id => 4,
content => 'some more content'
[2] =>
id => 7
content => 'some content'
[3] =>
id => 3,
content => 'some other content'
)
Upvotes: 0
Views: 762
Reputation: 75645
You'd significantly help yourself if source array keys would be equal to Ids. That'd speed things up. But for now this would make your source data ordered accoring to your sort array values):
$res = array();
foreach( $sortArray as $sortId ) {
foreach( $srcArray as $item ) {
if( $item['id'] == $sortId ) {
$res = $item;
break;
}
}
}
EDIT
if you'd have Id used as keys, then second foreach()
would be of no use:
$res = array();
foreach( $sortArray as $sortId ) {
$res[] = $srcArray[ $sortId ];
}
Upvotes: 4
Reputation: 12537
This solution uses usort
:
$sarray = array(2, 4, 7, 3);
$sarray = array_flip($sarray);
usort($posts, function($a, $b) use($sarray) {
// TODO: check if the array-index exists ;)
$index_a = $sarray[$a['id']];
$index_b = $sarray[$b['id']];
return $index_a - $index_b;
});
var_dump($posts);
Since I'm using closures you need PHP 5.3 to use it like that. If you need to have 5.2 compatibility, you probably have to use create_function
.
Upvotes: 1