从PHP数组访问数据

时间:2014-05-11 14:51:23

标签: php arrays

我有一个数组如下

$user_followers = [
    [
        'user_id'   => '1',
        'followers' => ['3', '4', '5']
    ],
    [
        'user_id'   => '2',
        'followers' => ['1', '5']
    ],
    [
        'user_id'   => '3',
        'followers' => ['1', '5', '4']
    ],
    [
        'user_id'   => '4',
        'followers' => ['3', '1', '5']
    ],
    [
        'user_id'   => '5',
        'followers' => ['1', '2', '4']
    ],
];

我需要做的是根据user_id值获取关注者数据数组,因此如果我的user_id为2,它将返回一个包含followers数组数据的数组。我不确定是否需要重新组织我的数组结构来执行此操作。

3 个答案:

答案 0 :(得分:2)

您可以使用array_column()轻松地将followers键入所有user_id,然后您可以按用户ID访问关注者:

$followers = array_column($user_followers, 'followers', 'user_id');

print_r($followers[2]);

给出了(Demo):

Array
(
    [0] => 1
    [1] => 5
)

只要密钥是唯一的(这是array_column的第三个参数,并且这里的user_id听起来像一个唯一的ID)就行了。

答案 1 :(得分:2)

如果你的版本是php< 5.5你不能使用array_column

Fatal error: Call to undefined function array_column()

所以你可以创建自己的功能:

if ( !function_exists('array_column') ) {
  function array_column( $collection, $field, $keyfield = null, $desired_id = null ) {
    $items = array();
    foreach ( $collection as $k => $item ) {
      $key = $keyfield ? $item[$keyfield] : $k;
        if( $desired_id == $key){     
            $items[] = $item[$field];
        }
    }
    return $items;
  }
}

var_dump(array_column($user_followers, 'followers', 'user_id', 2));

结果:

array (size=1)
  0 => 
    array (size=2)
      0 => string '1' (length=1)
      1 => string '5' (length=1)

示例 - Demo

答案 2 :(得分:1)

首先,您的数组应该如下所示:

$users = array(
        array(
            'user_id'   => '1',
            'followers' => array('3', '4', '5')
        ),
        array (
            'user_id'   => '2',
            'followers' => array('1', '5')
        ),
        array(
            'user_id'   => '3',
            'followers' => array('1', '5', '4')
        ),
        array(
            'user_id'   => '4',
            'followers' => array('3', '1', '5')
        ),
        array(
            'user_id'   => '5',
            'followers' => array('1', '2', '4')
        ),
    );

您可以创建如下函数:

// Returns the array of user data
function getUserFollowers($users, $desired_id) {
    foreach($users as $user) {
        if ( $user['user_id'] == $desired_id ) {
            return $user['followers'];
        }
    }
}

参数 $ users 是所有用户的数组, $ id 是您要查找的用户的ID。 foreach循环遍历所有用户并检查所有用户的ID。如果匹配,则返回关注者数组。

注意,如果阵列很大,这个过程会占用大量内存。你从哪里加载这些数据?

相关问题