来自PHP关联数组的JSON

时间:2016-02-09 12:36:59

标签: php arrays json.net

我有一个关联数组,如下所示

enable

我需要像这样的json

$arraySapmle =  array ("benz" => "car","bmw" => "car","volvo" = "car",
                      "delhi" => "place", "newyork" => "place", "tokyo" =>"place" );

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

您最接近该结构的是让每个顶级属性(car, place)包含一个具有name属性的对象数组:

$restructured=[];
foreach($arraySample as $key=>$val)
    $restructured[$val][]=['name'=>$key];
echo json_encode($restructured, JSON_PRETTY_PRINT);

输出:

{
    "car": [
        {
            "name": "benz"
        },
        {
            "name": "bmw"
        },
        {
            "name": "volvo"
        }
    ],
    "place": [
        {
            "name": "delhi"
        },
        {
            "name": "newyork"
        },
        {
            "name": "tokyo"
        }
    ]
}

答案 1 :(得分:0)

这将生成一个数组,其中包含“car”和“place”的键,其值为汽车和地点的数组:

$array = array();
foreach($arraySample as $key => $value){
  if(!isset($array[$value])) $array[$value] = array();
  $array[$value][] = $key;
}
$json = json_encode($array);

这不是你要求的数据结构,但它是有意义的。