Asked  10 Months ago    Answers:  5   Viewed   7 times

For example I have the following code:

$sample = array(apple, orange, banana, grape);

I want to rearrange this array, by making $sample[2] the new $sample[0], while keeping the same order throughout the array.

Output should be:

Array ( [0] => banana [1] => grape [2] => apple [3] => orange) 

 Answers

3

Use array_shift() as many times as you need...

$sample = array('apple', 'orange', 'banana', 'grape');

$fruit = array_shift($sample);
$sample[] = $fruit;
// now $sample will be array('orange', 'banana', 'grape', 'apple');

So say you want to make a function:

function rearrange_array($array, $key) {
    while ($key > 0) {
        $temp = array_shift($array);
        $array[] = $temp;
        $key--;
    }
    return $array;
}

Now, using rearrange_array($sample, 2) you can rearrange the sample array to your desired output.

Wednesday, August 4, 2021
 
1

You could use array_filter:

$filtered = array_filter($array, function($v) { return $v['type'] == 'folder'; });
Thursday, April 1, 2021
 
axiomer
 
1
usort($array['javascript']['core'], function($a, $b) {
    return $a['weight'] - $b['weight'];
});
Thursday, April 1, 2021
 
Niels
 
1
function cmp($a, $b)
{

$sizes = array(
"XXS" => 0,
"XS" => 1,
"S" => 2,
"M" => 3,
"L" => 4,
"XL" => 5,
"XXL" => 6
);

$asize = $sizes[$a];
$bsize = $sizes[$b];

if ($asize == $bsize) {
    return 0;
}

return ($asize > $bsize) ? 1 : -1;
}

usort($your_array, "cmp");
Thursday, April 1, 2021
 
Blur
 
3

Use multi-byte string functions. There is a function called strcoll which seems to suit your needs.

More info:

  • On how to sort an array of UTF-8 strings
  • How to sort an array of UTF-8 strings?

EDIT: added Peter's working code, below

setlocale(LC_COLLATE, 'sk_SK.utf8');

usort($fb_friends['data'], 'custom_sort');

function custom_sort($a, $b) {
    return strcoll ($a['last_name'], $b['last_name']);
}

foreach ($fb_friends['data'] as $friend) {
    echo '<br>';
    echo $friend['name'];
}
Saturday, May 29, 2021
 
Packy
 
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :