我有一个关联数组,如下所示
enable
我需要像这样的json
$arraySapmle = array ("benz" => "car","bmw" => "car","volvo" = "car",
"delhi" => "place", "newyork" => "place", "tokyo" =>"place" );
有什么想法吗?
答案 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);
这不是你要求的数据结构,但它是有意义的。