Put a data first in a php key-value object


I'm not very used to php and I need to place a key-value on an object. I have this:


I need to place this at the beginning:

"no_job":"Please select an option"

That is, in the end I would have something like this:

{"no_job":"Please select an option", "5ba68024f109b61fe95ccd02":"asistent","5bd0c379f109b673c11c9502":"seller","5be0addcf109b64c847abd26":"coder","5be0b26af109b64c847abd2c":"teacher","5becab8cf109b676d935e289":"engineer"}

Try with:

 $job_list["no_job"] = "Please select an option";
 array_unshift($job_list, $job_list["no_job"]);

However the data is duplicated at the end:

{"no_job":"Please select an option", "5ba68024f109b61fe95ccd02":"asistent","5bd0c379f109b673c11c9502":"seller","5be0addcf109b64c847abd26":"coder","5be0b26af109b64c847abd2c":"teacher","5becab8cf109b676d935e289":"engineer", "no_job":"Please select an option"}

What do you recommend me to do?

asked by Cesar Jr Rodriguez 22.11.2018 в 20:41

2 answers


In practice, it does not make sense to place the properties of a json object in a certain order, but if you really need it that way you can try array_merge , attaching the initial object to the new property.


$test = array(
$test2 = array('x'=>6);
$test = array_merge($test2,$test);
echo json_encode($test);

where the result will be

answered by 22.11.2018 в 20:57

If you need to control the order of the elements, I would recommend using a sequential array instead of an associative one:

$arr = [
    ["5ba68024f109b61fe95ccd02", "asistent"],
array_unshift($arr, ["no_job", "Please select an option"]);

In this way, if you serialize it in PHP with JSON and deserialize it with another language, it will always keep the order of the elements; whereas an associative array could be read as a dictionary in another language, which might not maintain the order of the elements.

answered by 22.11.2018 в 21:09