[英]PHP array and json_encode (separated with comma)
我实际上是想把PHP数组转换为JavaScript数组,然后将其转换为正确的格式。 这就是我所拥有的
我的PHP数组存储在$data
(这来自SQLserver查询)中,我正在使用json_encode
将其转换为JavaScript数组。
这是代码$javaarray = json_encode($data);
当我echo
结果时,这就是我得到的
{"VERTICAL":"PROVISIONING","dcount":381890}
{"VERTICAL":"BILL DELIVERY","dcount":171169}
{"VERTICAL":"BILLING","dcount":45197}
{"VERTICAL":"RISK AND CREDIT","dcount":51533}
{"VERTICAL":"CUSTOMER ACCOUNTING","dcount":136097}
{"VERTICAL":"AIRTEL MONEY","dcount":7826}
{"VERTICAL":"ANALYTICS","dcount":2946}
{"VERTICAL":"CONTROLS","dcount":5615}
现在,我想获取dcount
部分,仅将其以以下格式反馈给我的jQuery函数
[381890,171169,45197,51533,136097,7826,2946,5615]
我尝试使用implode(), join()
但是不知何故与上述格式之间的距离越来越近。
我正在发布
$array = array($data);
print_r($array);
结果也
Array ( [0] => Array ( [VERTICAL] => PROVISIONING [dcount] => 381890 ) ) Array ( [0] => Array ( [VERTICAL] => BILL DELIVERY [dcount] => 171169 ) ) Array ( [0] => Array ( [VERTICAL] => BILLING [dcount] => 45197 ) ) Array ( [0] => Array ( [VERTICAL] => RISK AND CREDIT [dcount] => 51533 ) ) Array ( [0] => Array ( [VERTICAL] => CUSTOMER ACCOUNTING [dcount] => 136097 ) ) Array ( [0] => Array ( [VERTICAL] => AIRTEL MONEY [dcount] => 7826 ) ) Array ( [0] => Array ( [VERTICAL] => ANALYTICS [dcount] => 2946 ) ) Array ( [0] => Array ( [VERTICAL] => CONTROLS [dcount] => 5615 ) )
试试这个
$dcounts = array();
foreach ($data as $row) {
$dcounts[] = $row['dcount'];
}
$javaarray = json_encode($dcounts);
$dcounts = json_encode(array_map(function($v) { return $v['dcount'] }, $javaarray));
$data = '{"VERTICAL":"PROVISIONING","dcount":381890}
{"VERTICAL":"BILL DELIVERY","dcount":171169}
{"VERTICAL":"BILLING","dcount":45197}
{"VERTICAL":"RISK AND CREDIT","dcount":51533}
{"VERTICAL":"CUSTOMER ACCOUNTING","dcount":136097}
{"VERTICAL":"AIRTEL MONEY","dcount":7826}
{"VERTICAL":"ANALYTICS","dcount":2946}
{"VERTICAL":"CONTROLS","dcount":5615}';
//split data into array
$keywords = preg_split("/[\n]+/", $data);
//convert into proper json format
$jsonobject = implode(',',$keywords);
$jsonobject = '['.$jsonobject.']';
//convert json into array
$array = json_decode($jsonobject);
//for each and save dcount value
$dcount = array();
foreach($array as $row){
$dcount[] = $row->dcount;
}
//again convert dcount values into json
$dcountjson = json_encode($dcount);
print_r($dcountjson);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.