Deano
Deano

Reputation: 12200

PHP Prepend two elements to associative array

I have the following array, I'm trying to append the following ("","--") code

Array
(
    [0] => Array
        (
            [Name] => Antarctica
        )

)

Current JSON output

[{"Name":"Antarctica"}]

Desired output

{"":"--","Name":"Antarctica"}]

I have tried using the following:

$queue = array("Name", "Antarctica");
array_unshift($queue, "", "==");

But its not returning correct value.

Thank you

Upvotes: 1

Views: 228

Answers (5)

LSerni
LSerni

Reputation: 57418

The translation of PHP Array to JSON generates a dictionary unless the array has only numeric keys, contiguous, starting from 0.

So in this case you can try with

$queue = array( 0 => array( "Name" => "Antarctica" ) );

$queue[0][""] = "--";

print json_encode($queue);

If you want to reverse the order of the elements (which is not really needed, since dictionaries are associative and unordered - any code relying on their being ordered in some specific way is potentially broken), you can use a sort function on $queue[0], or you can build a different array:

$newqueue = array(array("" => "--"));
$newqueue[0] += $queue[0];

which is equivalent to

$newqueue = array(array_merge(array("" => "--"), $queue[0]));

This last approach can be useful if you need to merge large arrays. The first approach is probably best if you need to only fine tune an array. But I haven't ran any performance tests.

Upvotes: 2

Tim Lewis
Tim Lewis

Reputation: 29297

Try this:

$queue = array(array("Name" => "Antarctica")); // Makes it multidimensional 
array_unshift($queue, array("" => "--"));

Edit

Oops, just noticed OP wanted a Prepend, not an Append. His syntax was right, but we was missing the array("" => "--") in his unshift.

Upvotes: 1

litechip
litechip

Reputation: 336

var_dump(array_merge(array(""=>"--"), $arr));

Upvotes: 0

yuriy.stos
yuriy.stos

Reputation: 687

You can try this :

$queue = array("Name" => "Antarctica");
$result = array_merge(array("" => "=="), $queue);

Upvotes: 0

BrokenBinary
BrokenBinary

Reputation: 7889

You can prepend by adding the original array to an array containing the values you wish to prepend

$queue = array("Name" => "Antarctica");
$prepend = array("" => "--");
$queue = $prepend + $queue;

You should be aware though that for values with the same key, the prepended value will overwrite the original value.

Upvotes: 4

Related Questions