我通常有这样的数组
(int) 0 => abc,
(int) 1 => def,
(int) 2 => ghi
如果我使用json_encode,它将成为
["abc", "def", "ghi"]
这对jquery自动完成非常有用
$(function() {
var availableTags = <?php echo json_encode($companyList); ?>;
$("#CompanyName").autocomplete({
source: availableTags,
delay: 10
});
});
但是现在,我需要更多数据,我看看jquery自动完成示例,数据必须看起来像这样
var company = [
{
value: "jquery",
label: "jQuery",
name: "the write less, do more, JavaScript library",
address: "jquery_32x32.png",
city: "xxxxx",
},
{
value: "jquery-ui",
label: "jQuery UI",
name: "the write less, do more, JavaScript library",
address: "jquery_32x32.png",
city: "xxxxx",
},
{
value: "sizzlejs",
label: "Sizzle JS",
name: "the write less, do more, JavaScript library",
address: "jquery_32x32.png",
city: "xxxxx",
}
];
如何以json_encode(或任何其他方式)来改变像这样的PHP数组
array(
(int) 0 => array(
'Company' => array(
'id' => '19',
'group_id' => '1',
'name' => 'Harts Harts',
'address' => 'xxx NE xxxth Street',
'city' => 'Shoreline',
'state' => 'WA',
'zip' => '98155',
'country' => '',
)
),
(int) 1 => array(
'Company' => array(
'id' => '21',
'group_id' => '1',
'name' => 'Andy Robin',
'address' => 'xxx xxxth Ave NE',
'city' => 'Bellevue',
'state' => 'WA',
'zip' => '98004',
'country' => '',
)
)
)
看起来像jquery自动完成源,因为如果我直接使用json_encode($ company),它将成为对象,我不能将它用于自动完成。
这个数组将有大约2500个数据 谢谢
答案 0 :(得分:1)
$return_arr = array();
$company_arr = array(
(int) 0 => array(
'id' => '19',
'group_id' => '1',
'name' => 'Harts Harts',
'address' => 'xxx NE xxxth Street',
'city' => 'Shoreline',
'state' => 'WA',
'zip' => '98155',
'country' => '',
),
(int) 1 => array(
'id' => '21',
'group_id' => '1',
'name' => 'Andy Robin',
'address' => 'xxx xxxth Ave NE',
'city' => 'Bellevue',
'state' => 'WA',
'zip' => '98004',
'country' => '',
)
);
foreach ($company_arr as &$company) {
array_push($return_arr,$company);
}
echo json_encode($return_arr);
输出:
[{"id":"19","group_id":"1","name":"Harts Harts","address":"xxx NE xxxth Street","city":"Shoreline","state":"WA","zip":"98155","country":""},{"id":"21","group_id":"1","name":"Andy Robin","address":"xxx xxxth Ave NE","city":"Bellevue","state":"WA","zip":"98004","country":""}]
注意:要用于jquery自动填充,您需要在返回的value
中添加label
或json
字段。您目前没有这些字段。
答案 1 :(得分:0)
使用jQuery parseJSON方法来解析从PHP获得的json。
var obj = jQuery.parseJSON( 'json_string_here' );
答案 2 :(得分:0)
api jquery-ui:autocomplete
阅读自动完成的api后:
$companyList = array();
foreach($companies as $company){
array_push( $companyList, $company["Company"]["name"]);
}
返回:
["Harts Harts","Andy Robin"]
自动完成功能可以使用此计划旧数组或对象属性数组label
和value
,如下所示:
[{label:"Harts Harts",value:"Harts Harts"},{label:"Andy Robin",value:"Andy Robin"}]
如果您还有其他问题,请询问。