1

I have an array which is use the key as table header dynamically, I wanted to re-arrange the following in this order:

fullname, age, email, tel, project, type, purpose, budget, income 

default array element

Array
(
    [type] => Plastic
    [purpose] => Sell
    [budget] => 401,000-500,000
    [income] => 12,000-29,999
    [fullname] => John Smith
    [age] => 30
    [email] => john@email.com
    [tel] => 12345678
    [project] => Project A
)

Can it be done by move it manually in code?

conmen
  • 2,377
  • 18
  • 68
  • 98
  • you need it to do using loop, sorting is allwed only in a order `A-Z` - `0-9` asc, desc. for custom order loop is the way to go – Saqueib Dec 15 '14 at 06:57

4 Answers4

1
$arr = array();// THIS IS YOUR INPUT ARRAY.
$sort = array('fullname', 'age', 'email', 'tel', 'project', 'type', 'purpose', 'budget', 'income');
$n = array();
foreach ($sort as $v) {
  $n[$v] = $arr[$v];
}
echo '<pre>';
print_r($n);
echo '</pre>';

Note: This is a sample, you can apply it in loop also.

Working Example

Pupil
  • 23,834
  • 6
  • 44
  • 66
0

Please check below link

Sort an Array by keys based on another Array?

It is used to array reorder using another array

function sortArrayByArray(Array $array, Array $orderArray) {
    $ordered = array();
    foreach($orderArray as $key) {
        if(array_key_exists($key,$array)) {
            $ordered[$key] = $array[$key];
            unset($array[$key]);
        }
    }
    return $ordered + $array;
}

Check this function in above link

Community
  • 1
  • 1
Deeban Babu
  • 729
  • 1
  • 15
  • 49
0

Where $original_data is the variable containing the array you have outlined in your question, you can use this logic to re-sort it based on a set of column names:

$new_sort_order = array(
    'fullname',
    'age',
    'email',
    'tel',
    'project',
    'type',
    'purpose',
    'budget',
    'income',
);

$sorted_data = array();
foreach ($new_sort_order as $column_title) {
    if(isset($original_data[$column_title])) {
        $sorted_data[$column_title] = $original_data[$column_title];
    }
}

var_export($sorted_data);
Manmaru
  • 578
  • 3
  • 8
0

Put the required order of keys in an array, and foreach item in that key array, place its respective content from the old array. Finally the new array will be in the order mentioned in $arr.

//$oldArr
Array 
    (
        [type] => Plastic
        [purpose] => Sell
        [budget] => 401,000-500,000
        [income] => 12,000-29,999
        [fullname] => John Smith
        [age] => 30
        [email] => john@email.com
        [tel] => 12345678
        [project] => Project A
    )

$oldArr contains the key => value array as mentioned above

$arr = array('fullname','age','email','tel','project','type','purpose','budget','income');
foreach($arr as $a)
{
   if($oldArr[$a])
    $newArr[$a] = $oldArr[$a];
}
Venkata Krishna
  • 1,768
  • 2
  • 14
  • 21