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] => [email protected]
    [tel] => 12345678
    [project] => Project A
)

Can it be done by move it manually in code?

1
  • 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 Commented Dec 15, 2014 at 6:57

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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);

Comments

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] => [email protected]
        [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];
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.