EagleH
EagleH

Reputation: 107

Json array move to top

I'm showing the JSON with this code:

<?php
$result = array();
array_push($result,
    array("id" => 1, "title" => "text 1"),
    array("id" => 2, "title" => "text 2"),
    array("id" => 3, "title" => "text 3"),
    array("id" => 4, "title" => "text 4")
);
echo json_encode($result);
?>

I want to move the id 3 to the top. Is this possible? How can I do it?

The result should be like this:

[
    {
    "id": 3,
    "title": "text 3"
    },
    {
    "id": 1,
    "title": "text 1"
    },
    {
    "id": 2,
    "title": "text 2"
    },
    {
    "id": 4,
    "title": "text 4"
    }
]

Upvotes: 1

Views: 198

Answers (2)

Don&#39;t Panic
Don&#39;t Panic

Reputation: 41820

You can sort the array before JSON encoding it.

$move_to_top = 3;

usort($result, function($a, $b) use ($move_to_top) {
    if ($a['id'] == $move_to_top) return -1;
    if ($b['id'] == $move_to_top) return 1;
    return $a['id'] - $b['id'];
});

This does sort the array. If you want to leave the current order alone other than moving the one item, you can iterate it, and when you find the id you want, unset the current key and then append the item to the beginning of the array.

$move_to_top = 3;

foreach($result as $key => $item) {
    if ($item['id'] == $move_to_top) {
        unset($result[$key]);
        array_unshift($result, $item);
        break;
    }
}

json_encode after you've moved the item to the top.

echo json_encode($result);

Upvotes: 2

steffen
steffen

Reputation: 17028

array_splice can help:

$out = array_splice($result, 2, 1);
array_splice($result, 0, 0, $out);

Result:

[{"id":3,"title":"text 3"},{"id":1,"title":"text 1"},{"id":2,"title":"text 2"},{"id":4,"title":"text 4"}]

Upvotes: 2

Related Questions