[英]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.