PHP数组和json_encode(用逗号分隔)

时间:2013-11-28 09:41:24

标签: javascript php arrays

我真的很想把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 ) )

3 个答案:

答案 0 :(得分:1)

尝试这样的事情

$dcounts = array();

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

$javaarray = json_encode($dcounts);

答案 1 :(得分:1)

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

答案 2 :(得分:1)

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