Php-Sort Array Based on Another Array

Sort an Array by keys based on another Array?

Just use array_merge or array_replace. array_merge works by starting with the array you give it (in the proper order) and overwriting/adding the keys with data from your actual array:

$customer['address']    = '123 fake st';
$customer['name'] = 'Tim';
$customer['dob'] = '12/08/1986';
$customer['dontSortMe'] = 'this value doesnt need to be sorted';

$properOrderedArray = array_merge(array_flip(array('name', 'dob', 'address')), $customer);
// or
$properOrderedArray = array_replace(array_flip(array('name', 'dob', 'address')), $customer);

// $properOrderedArray: array(
// 'name' => 'Tim',
// 'dob' => '12/08/1986',
// 'address' => '123 fake st',
// 'dontSortMe' => 'this value doesnt need to be sorted')

PS: I'm answering this 'stale' question, because I think all the loops given as previous answers are overkill.

Sort array elements based on another array's keys

How about this? Using array_replace():

<?php
$arr1 = array('0' => 'John', '1' => 'George', '2' => 'James', '3' => 'Harry');
$arr2 = array('0' => '12', '1' => '8', '2' => '34', '3' => '23');
arsort($arr2);
var_dump(array_replace($arr2, $arr1)); // array(4) { [2]=> string(5) "James" [3]=> string(5) "Harry" [0]=> string(4) "John" [1]=> string(6) "George" }

Demo

PHP - Sort array with another array

$ordered_fruits = array();
foreach($order as $value) {

if(array_key_exists($value,$fruits)) {
$ordered_fruits[$value] = $fruits[$value];
}
}

Sorting array in PHP based on another array indexes

Try this

$new_records = array();
foreach( $sort as $id => $pos ) {
foreach( $records as $record ) {
if( $record[ 'id' ] == $id ) {
$new_records[] = $record;
break;
}
}
}

Javascript - sort array based on another array

One-Line answer.

itemsArray.sort(function(a, b){  
return sortingArr.indexOf(a) - sortingArr.indexOf(b);
});

Or even shorter:

itemsArray.sort((a, b) => sortingArr.indexOf(a) - sortingArr.indexOf(b));

PHP - Sort multi-dimensional array by another array

There is no built-in function for this in PHP and i am unable to think of any custom function, which would do this using usort. But array_map is simple enough, imo, so why not use it instead?

$sorted = array_map(function($v) use ($data) {
return $data[$v - 1];
}, $order);


Related Topics



Leave a reply



Submit