Jump to content

[SOLVED] sort an array by the values of keys in another array


diamondnular

Recommended Posts

Hi folks,

 

I have two arrays:

$e = Array

(

    [0 ] => Array

        (

            [id] => 3

            [value] => a

        )

 

    [1] => Array

        (

            [id] => 2

            [value] => b

        )

 

    [2] => Array

        (

            [id] => 5

            [value] => c

        )

 

)

and

$d = Array

(

    [0 ] => 5

    [1] => 2

    [2] => 3

)

 

What I want to do is to sort array $e with values of 'id' of its elements to be the same order as array $d, meaning that after sorting, new array will be

$f = Array

(

    [0 ] => Array

        (

            [id] => 5

            [value] => c

        )

 

    [1] => Array

        (

            [id] => 2

            [value] => b

        )

 

    [2] => Array

        (

            [id] => 3

            [value] => a

        )

 

)

 

Here is what I did:

<?php
$a = array('id' => 3,'value' =>'a');
$b = array('id' => 2,'value' =>'b');
$c = array('id' => 5,'value' =>'c');
$d = array('5','2','3');
print_r($d);

$e = array();
array_push($e,$a);
array_push($e,$b);
array_push($e,$c);
print_r($e);

$f = array();
foreach ($d as $key) {
foreach ($e as $x) {
	if ($x[id] == $key) array_push($f,$x);
}
}
print_r($f);
?>

The code does work, and gave me the result I want. But I have two questions here:

 

1. I got a notice: Use of undefined constant id - assumed 'id'. That should be

$x[id] == $key

How do I fix this notice?

 

2. More important: I think there must be an easier way to do the above, using asort or usort or some function that I maybe not know of. The above is doable, but it is too handy, and not very efficient in my opinion.

 

You guys masters in php have any advice? Remember, I am just novice in php :)

 

Thanks,

 

D.

usinf usort()

<?php

function mysort($a, $b)
{
global $d;
return array_search($a['id'], $d) - array_search($b['id'], $d);
}

usort($e, 'mysort');
echo '<pre>', print_r($e, true), '</pre>';

?>

 

usinf usort()

<?php

function mysort($a, $b)
{
global $d;
return array_search($a['id'], $d) - array_search($b['id'], $d);
}

usort($e, 'mysort');
echo '<pre>', print_r($e, true), '</pre>';

?>

 

 

This code works! It takes generally half of the running time of my code. I think it is much more efficient than mine. Thanks Barand.

 

D.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.