强制json_encode对所有值使用相同的键

时间:2014-06-26 11:22:06

标签: php arrays json object

我有像

这样的php数组
array("Some Name","Some Othername")

我希望有一个像这样的json对象

[{" value":" Some name"},{" value":" Some Othername"}]

解决方案是什么?!

3 个答案:

答案 0 :(得分:1)

试试这段代码:

$test = array("Some Name","Some Othername");
$temp = array();
foreach($test as $i=>$k)
{
    $temp[]['value'] = $k;
}
print_r(json_encode($temp));

另一种选择:

$test = array("Some Name","Some Othername");
echo json_encode(array_map(function($temp){return array("value"=>$temp);},$test));

答案 1 :(得分:0)

创建您的PHP数组,如:

array(
  array("value" => "Some Name"),
  array("value" => "Some Othername")
);

答案 2 :(得分:0)

试试这种方式

$array1 = array("Some Name","Some Othername");
$arrar2 = array();
foreach($array1 as $value){
   $array2[] = array("value" => $value);
}
echo json_encode($array2);