简体   繁体   中英

PHP adding to a multidimensional array

I am setting up a Jquery autosuggest using ajax and I have a simple query to the database which returns 5 suggestions. The fields are company and id, so I get

$result['id']
$result['company']

for each row of the returned database suggestiions

This works fine and currently I loop over the results

foreach ($result as $item) {
$suggest[] = $item['company'];

}

echo json_encode($suggest);

I want though to add these so the company is a label and id is a value, something like

 "value": "A Company", "data": "20"

This I can then encode and use in my autosuggest.

Thanks in advance!

You have to save an array to main array like this

foreach ($result as $item) {
    $suggest[] = [
        'value' => $item['company'],
        'data' => $item['id'],
    ]
}

echo json_encode($suggest);

And it should return something like this

[
    {
        'value': 'Some value',
        'data' : item id
    }
]

i will recommend you create an array, next create 2 more arrays as values for the value and data keys. like this.

$arr=array();
$arr['value']=array();
$arr['data']=array();

while($suggest=mysql_fetch_assoc($result)){
    array_push($arr['value'],$suggest['id']);
    array_push($arr['data'],$suggest['company']);
}

echo "<pre>";
print_r($arr);

note that with this solution, if you delete an entry in either value or data be ready to delete the corresponding entry in the other array. others may be able to improve this or even offer a better approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM