0

I have this array $arr1

Array
(
    [0] =>  [col1]
    [1] =>  [col2]
    [2] =>  [col3]
)

I have another array $arr2 as

Array
(
    [0] => Array
        (
            [col3] => data1
            [col2] => data2
            [col1] => data3
        )

    [1] => Array
        (
            [col2] => data1
            [col3] => data2
            [col1] => data3
        )
)

I need to sort this $arr2 keys as col1, col2 and col3 like as it is on $arr1.

I tried with array_multisort($arr1,$arr2) and the other way. Nothing worked. any help on this ?

2
  • I think that you'll have to write your own sorting function, but i'm curious to know if there are better solutions Commented Jul 27, 2013 at 8:17
  • possible duplicate of Reference: all basic ways to sort arrays and data in PHP Commented Jul 27, 2013 at 9:14

4 Answers 4

2

Using loop.

$keys = array_values($arr1);
$out = array();
foreach($arr2 as $ar){
    $outar = array();
    foreach($keys as $k){
        if(isset($ar[$k])){
            $outar[$k]=$ar[$k];
        }
    }
    $out[]=$outar;
}

The output array will be held in $out. See ideone.

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

3 Comments

There is no foreach..in loop in php. It should be foreach..as
@smm right you are. Using too much python these days. Forgetting PHP. Added a ideone link that shows it works.
yours is considerably more efficient.
0

You can do this with uksort and a closure (PHP 5.3+)

foreach($arr2 as &$array){
    uksort($array,function($a,$b) use ($arr1){
        return array_search($a, $arr1) - array_search($b, $arr1);
    });
}

1 Comment

your algorithm has n*n*n*log(n) complexity. n is the length of first array.
0
foreach ( $arr2 as $k => &$arr ) {
    ksort($arr);
}
print_r($arr2);

Use ksort with a foreach loop with value passed by reference.

4 Comments

I need to sort $arr2 not $arr1.
ksort like any other in-place sorts in php will return a boolean indicating the success. Thus you're overwriting $arr.
and $arr2 needs to be ordered using information coming from $arr1
@Prashanth, I don't see any comparison with $arr1 ?
0

if first array values are exactly the same as indexes in second one, try

$resarr = array();
foreach ($arr2 as $somearr) {
    $i = 0;
    $newarr = array();
    foreach ($somearr as $value) {
        $newarr[$arr1[$i]] = $value;
        $i++;
    }
    $resarr[] = $newarr;
}
$arr1 = $resarr;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.