在key = value处用键将值推入数组

时间:2017-02-16 19:47:26

标签: php mysql arrays sorting pdo

我有一个包含多个用户和位置数据的数据库。我把它们放在如下的数组中

id--username--lat-----lng
1 | user1  |  56.86 | 7.85
2 | user2  |  48.3  | 9.323
3 | user3  |  83.22 | 84.2
etc...

数组$ users看起来像:

$users = Array( [0] => ( [id] => 1[0] => 1[username] => user1[1] => user1[lat] => 56.86[2] => 56.86[lng] => 7.85[3] => 7.85)
[1] => ( [id] => 2[0] => 2[username] => user2[1] => user2[lat] => 48.3[2] => 48.3[lng] => 9.323[3] => 9.323)
[2] => ( [id] => 3[0] => 3[username] => user3[1] => user3[lat] => 83.22[2] => 83.22[lng] => 84.2[3] => 84.2))

我使用mylat和mylng计算每个用户的lat和lng的距离。 然后我想将值$ distn推送到位置/密钥id的数组$ users中,并带有用户ID的值,但我不知道如何:

    foreach ($users as $row) { //for each user in database calculate the distance and set it to the variable $distn

    $dist = 0.0;
        $x1 = $mylng;
        $x2 = $row['lng'];
        $y1 = $mylat;
        $y2 = $row['lat'];

        $dist = acos(sin($x1=deg2rad($x1))*sin($x2=deg2rad($x2))+cos($x1)*cos($x2)*cos(deg2rad($y2) - deg2rad($y1)))*(6378.137);
        $distn = FLOOR ( ROUND($dist,1) * 2 ) / 2 ;

      push $distn into $users where id=row['id'] // this is just a sample not real code

    }

这样阵列现在看起来应该是这样的:

$users = Array( [0] => ( [id] => 1[0] => 1[dist] => 3.0[1] => 3.0[username] => user1[2] => user1[lat] => 56.86[3] => 56.86[lng] => 7.85[4] => 7.85)
[1] => ( [id] => 2[0] => 2[dist] => 1.5[1] => 1.5[username] => user2[2] => user2[lat] => 48.3[3] => 48.3[lng] => 9.323[4] => 9.323)
[2] => ( [id] => 3[0] => => 3[dist] => 1.0[1] 1.0[username] => user3[2] => user3[lat] => 83.22[3] => 83.22[lng] => 84.2[4] => 84.2))

值$ distn添加了键" dist"在关键" id"之后与每个用户的价值。 如果这有效,我想对数组进行排序,以便用户具有最低的" dist"首先显示:

user3 1km distance
user2 1.5km distance
user1 3km distance

我怎么能做到这一切?谢谢你的帮助:)

1 个答案:

答案 0 :(得分:1)

对于第一部分,请使用$key => $value的{​​{1}}语法:

foreach()

对于排序,我会提取列并按原样对原始文件进行排序:

foreach ($users as $key => $row) {
    // code
    $users[$key]['dist'] = $distn;
}

此外,由于您正在使用关联数组,请考虑:

array_multisort(array_column($users, 'dist'), SORT_ASC, $users);