0

I have array like this

<?php
$sliders=array(
1=>array('url'=>"url1.com",'image'=>"img1.jpg"),
2=>array('url'=>"url2.com",'image'=>"img2.jpg"),
3=>array('url'=>"url3.com",'image'=>"img3.jpg"),
4=>array('url'=>"url4.com",'image'=>"img4.jpg"),
5=>array('url'=>"url5.com",'image'=>"img5.jpg")
);
foreach($sliders as $sKey=>$sVal)
{
    echo $sKey.'=>'.$sVal['url'].' image=>'.$sVal['image'].'<br>';
}
?>

And my sorting key is

$sort[]='2,4,5,3,1';

And I want result like this.

array(
1=>array('url'=>"url2.com",'image'=>"img2.jpg"),
2=>array('url'=>"url4.com",'image'=>"img4.jpg"),
3=>array('url'=>"url5.com",'image'=>"img5.jpg"),
4=>array('url'=>"url3.com",'image'=>"img3.jpg"),
5=>array('url'=>"url1.com",'image'=>"img1.jpg"));

How can I sorting Array like this?

Thanks.

0

1 Answer 1

2

I cannot believe that you did not find this yourself...

<?php
$newArray = array();

$sortArray = explode(',', $sort[0]);
$i = 1;
foreach ($sortArray as $s) {
    if (isset($sliders[$s])) {
        $newArray[$i] = $sliders[$s];
        $i++;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

This is nice, but key should be start from 1
I thought that it was a typo. Why is it not possible to start from zero? Anyway: updated the snippet.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.