简体   繁体   中英

php encode json array just first column

I need to enconde just the first column of an array with n rows,

Array
 (
[0] => Array
    (
        [FamilyName] => Dikkartan, Bartu
        [Balance] => -2446.91
        [Mobile] => 0444497
        [HAddress] => 2/6 Tramsway Street
        [HSuburb] => Rosebery
        [HState] => NSW
        [HPCode] => 

    )

[1] => Array
    (
        [FamilyName] => King, Alan & Luka
        [Balance] => -1676
        [Mobile] => 0433 6090
        [HAddress] => 46/12 Hayberry Street
        [HSuburb] => Crows Nest
        [HState] => NSW
        [HPCode] => 

    ) ...

so I need to make an array just with the first value [familyName], - I want to have this to use with a jquery autocomplete, so after having the name selected from autocomplete, I use this name to search again in the complete array and fill some textfields with the data from the array

  • I need to search in the array as data is taken from sql, but I cannot search in the db, just use the array data,

  • Is this a good path or what other path should I take to do some autocomplete for the name and then have my textfields filled with the data from that array

thanks a lot!

Using array_map you can reduce the array to just that element.

$familyNames = array_map(function($object) {
    return $object['FamilyName'];
}, $objects);

json_encode($familyNames);

This uses an anonymous function available in php 5.3 otherwise you need to use create_function or a reference to an existing function you've created. See the PHP callback documentation.

create_function('$object', 'return $object["FamilyName"];')

Alternatively you could use a simple foreach loop:

$familyNames = array();
foreach($objects as $object)
    $familyNames[] = $object['FamilyName'];

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