需要正确的JSON

时间:2019-06-13 11:55:07

标签: php arrays json

我需要以“属性和值”形式显示数据,但是获取的数据是直接形式。

我正在尝试

在此格式中获取数据

{"FirstName":"sbncf","EmailAddress":"jscn@jnsc.cs","LastName":"jj","Phone":"653736","SearchBy":"jhjnjn"}

但是我需要此表格

$data_string = '[{"Attribute":"FirstName","Value":"Bret"},{"Attribute":"LastName","Value":"Lee"},{"Attribute":"EmailAddress","Value":"bret.lee@australia.com"},{"Attribute":"Phone","Value":"8888888888"},{"Attribute":"SearchBy","Value":"Phone"}]';

我正在使用AJAx并使用它

$data_string =  json_decode(json_encode($_POST));

enter image description here

1 个答案:

答案 0 :(得分:0)

您需要将数据存储到另一个数组中,新数组必须包含AttributeValue索引,例如以下示例:

// testing $_POST data
$post = array();
$post['FirstName'] = 'sbncf';
$post['EmailAddress'] = 'jscn@jnsc.cs';
$post['LastName'] = 'jj';

$newArray = array(); // initialize new array
$i = 0;
foreach ($post as $key => $value) {
    $newArray[$i]['Attribute'] = $key;
    $newArray[$i]['Value'] = $value;
    $i++;
}

//use json_encode here:
$data_string =  json_encode($newArray);
echo $data_string; 

结果:

[{"Attribute":"FirstName","Value":"sbncf"},{"Attribute":"EmailAddress","Value":"jscn@jnsc.cs"},{"Attribute":"LastName","Value":"jj"}]