2013-11-28 108 views
-1

我從字面上破解我的頭隱蔽PHP的數組的JavaScript數組轉換同樣以正確的格式。這是我的PHP陣列和json_encode(用逗號分隔)

我的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))

+3

在哪種語言做你需要建立dcounts的陣列? – Aioros

+0

Java作爲我需要傳遞給我的Java函數... –

+0

Javascript功能來精確.. –

回答

1

嘗試是這樣的

$dcounts = array(); 

foreach ($data as $row) { 
    $dcounts[] = $row['dcount']; 
} 

$javaarray = json_encode($dcounts); 
1
$dcounts = json_encode(array_map(function($v) { return $v['dcount'] }, $javaarray)); 
+0

始終是一個很好的初步實踐,提供你的代碼的一些解釋。 – DontVoteMeDown

+0

Upvote漂亮的一個班輪 – bumperbox

0
$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);