PHP数组与JSON格式结构相同

时间:2015-10-07 10:27:07

标签: php

这里是我想在php数组中做的,以下是json格式:

JSON

    {
"suggestions": [
    { "value": "Alex - alex@email.com", "data": {"id": 1, "name": Alex } },
    { "value": "John - john@email.com", "data": {"id": 2, "name": John } },
    { "value": "Diaz - diaz@email.com", "data": {"id": 3, "name": Diaz } }
]
}

在我的php数组中查询结果:

array( 
0 => array('id'=>'1' 'email'=>'alex@email.com', 'name'=>'Alex'), 
1 => array('id'=>'2' 'email'=>'john@email.com', 'name'=>'John'),
2 => array('id'=>'3' 'email'=>'diaz@email.com', 'name'=>'Diaz')
);

您是否知道如何将我的php数组转换为JSON格式?

3 个答案:

答案 0 :(得分:0)

这可以帮助您获得JSON格式

 foreach($query as $key => $val){
    $json[$key]['value'] = $val['name']." - ".$val['email'];
    $json[$key]['data']["id"] = $val['id'];
    $json[$key]['data']["name"] = $val['name'];            
}

echo json_encode($json);

答案 1 :(得分:0)

你可以简单地使用json_encode();功能。

json_encode($array);

答案 2 :(得分:0)

foreach ($your_array as $key => $val) {
  foreach ($val as $k => $v) {
    if ($v == 'email') {
      //get the value of 'email' key in 'value'
      $newArr['suggestions']['value'] = current($v);
    }
    else {
      //if value is not email push it in 'data' key
      $newArr['suggestions']['data'] = $v;
    }
  }
}
//lastly encode the required array
echo json_encode($newArr);