在php的键值对象中添加数据

时间:2018-11-22 19:38:00

标签: php

我不太熟悉php,并且很难在键值对象中添加数据。我有这个:

 {"5ba68024f109b61fe95ccd02":"asistent","5bd0c379f109b673c11c9502":"seller","5be0addcf109b64c847abd26":"coder","5be0b26af109b64c847abd2c":"teacher","5becab8cf109b676d935e289":"engineer"}

我需要将此放在开头:

"no_job":"Please select an option"

所以我的数据必须是这样的:

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

我尝试过:

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

但是,该选项然后在对象的末尾重复:

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

我该如何实现?

2 个答案:

答案 0 :(得分:2)

PHP本身了解JSON,因此将其转换为数组,然后使用$originalArray = json_decode('{"5ba68024f109b61fe95ccd02":"asistent","5bd0c379f109b673c11c9502":"seller","5be0addcf109b64c847abd26":"coder","5be0b26af109b64c847abd2c":"teacher","5becab8cf109b676d935e289":"engineer"}', true); $newArray = array_merge(['no_job' => 'Please select an option'], $originalArray); print json_encode($newArray);

[class^="pl-"] {
   /* apply your rules */
   prop1: value1;
   prop2: value2;
}

[class^="pl-header"] {
   /* reset only for these */
   prop1: unset;
   prop2: unset;
}

答案 1 :(得分:2)

要在字符串的开头添加键和值,请使用json_decodetrue作为第二个参数将json转换为关联数组。然后,您可以使用union +运算符:

$job_list = json_decode(' {"5ba68024f109b61fe95ccd02":"asistent","5bd0c379f109b673c11c9502":"seller","5be0addcf109b64c847abd26":"coder","5be0b26af109b64c847abd2c":"teacher","5becab8cf109b676d935e289":"engineer"}
', true);
$job_list = ['no_job' => 'Please select an option'] + $job_list;
echo json_encode($job_list);

结果:

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