简体   繁体   English

PHP的编码JSON数组只是第一列

[英]php encode json array just first column

I need to enconde just the first column of an array with n rows, 我只需要围着n行数组的第一列,

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 因此,我需要使用第一个值[familyName]创建一个数组,-我想让它与jquery自动完成功能一起使用,因此从自动完成功能中选择名称后,我将使用该名称在完整数组中再次搜索,用数组中的数据填充一些文本字段

  • 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, 我需要在数组中搜索,因为数据是从sql中获取的,但是我无法在db中搜索,只能使用数组数据,

  • 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. 使用array_map可以将数组缩小为该元素。

$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. 这将使用php 5.3中提供的匿名函数,否则您需要使用create_function或对已创建的现有函数的引用。 See the PHP callback documentation. 请参阅PHP 回调文档。

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

Alternatively you could use a simple foreach loop: 另外,您可以使用一个简单的foreach循环:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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