从多维数组中组织或分组数据

时间:2015-10-13 11:54:42

标签: php arrays sorting multidimensional-array

我有一个多维数组,我很难尝试对特定需求进行分组和排序。这是数组:

Array ( 
    [0] => Array ( 
        [0] => Joe Smith 
        [1] => Array ( 
            [0] => 3 
            [1] => 9 
        ) 
    ) 
    [1] => Array ( 
        [0] => John Doe 
        [1] => Array ( 
            [0] => 6 
            [1] => 12 
        ) 
    ) 
    [2] => Array ( 
        [0] => Jack Frost 
        [1] => Array ( 
            [0] => 2 
            [1] => 4 
        ) 
    ) 
)

我想要做的是将数字从最小到最短(即2,3,4,6,9,12)排序,但也要保留与这些数字相关联的名称。例如:

2 (Jack Frost),
3 (Joe Smith),
4 (Jack Frost),
6 (John Doe),
9 (Joe Smith),
12 (John Doe)

有关如何按编号排序并将名称保持在一起的任何想法?感谢

更新1

以下是我用来按顺序列出数字的PHP代码:

$users = get_users();

$names = array();
$days = array();

foreach( $users as $user ) {
    $names[] = $user->display_name;
    $days[] = $user->member_day;
}

$result = array_map( null, $names, $days );

$mdays = array();
foreach( $days as $d ) {
    foreach( $d as $d2) {
        $mdays[] = $d2;
    }
}

for( $i; $i<=31; $i++ ) {
    if( in_array($i, $mdays) ) {
        echo $i . '<br>';
    }
}

在上面的代码中,$result打印出上面的数组。此外,for循环对“天”进行排序。

最终目标是拥有31个街区,并按名称填写数字块。

2 个答案:

答案 0 :(得分:0)

这样的事情应该有效,最后你可以通过数组

return array(
    'db' => array(
        // for primary db adapter that called
        // by $sm->get('Zend\Db\Adapter\Adapter')
        'username' => 'root',
        'password' => '',

        // to allow other adapter to be called by
        // $sm->get('db1') or $sm->get('db2') based on the adapters config.
        'adapters' => array(
            'db1' => array(
                'username' => 'root',
                'password' => '',
            ),
            'db2' => array(
                'username' => 'other_user',
                'password' => 'other_user_passwd',
            ),
        ),
    ),
);

答案 1 :(得分:0)

你可以做像

这样的事情
$result = [];
foreach ($arr as $key => $value) {
    foreach ($value[1] as $v) {
        $result[$v] = $value[0];
    }
}
ksort($result);
print_r($result);

<强>输出:

Array
(
    [2] => Jack Frost
    [3] => Joe Smith
    [4] => Jack Frost
    [6] => John Doe
    [9] => Joe Smith
    [12] => John Doe
)
  

注意:这个工作正常,直到阵列数组都不包含相同的键