简体   繁体   English

按多维数组值对多维数组排序

[英]Sort multidimensional array by multidimensional array value

I want to use the 'id' array of Array 1 to order all other sibling arrays in Array 2. The 'id' array is supposed to act as the schema for all other arrays in $array1 and $array2 . 我想使用数组1的'id'数组对数组2中的所有其他同级数组进行排序。'id'数组应该用作$array1$array2所有其他数组的架构。

This is easier explained with an example. 用一个例子更容易解释。

I have the following array, Array 1 : 我有以下数组,数组1:

Array
(
    [id] => Array
        (
            [0] => 1
            [1] => 3
            [2] => 2
        )

    [headline] => Array
        (
            [0] => test 1
            [1] => test 3
            [2] => test 2
        )
)

And another array, Array 2: 还有另一个数组Array 2:

Array
(
    [id] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

    [headline] => Array
        (
            [0] => tc test 1
            [1] => tc test 2
            [2] => tc test 3
        )
)

That I would like to look like the following: 我希望如下所示:

Array
(
    [id] => Array
        (
            [0] => 1
            [1] => 3
            [2] => 2
        )

    [headline] => Array
        (
            [0] => tc test 1
            [1] => tc test 3
            [2] => tc test 2
        )

)

Right now I'm trying to force it with foreach statements (and failing), but there has to be a better way. 现在,我正在尝试使用foreach语句(并且失败)强制使用它,但是必须有一种更好的方法。

This is a “fake” sort, because I fill an empty array through a foreach() loop, then I replace original array: 这是一种“伪”排序,因为我通过一个foreach()循环填充了一个空数组,然后替换了原始数组:

$array1 = [ 'id' => [ 1,3,2 ], 'headline' => [ 'test 1','test 3','test 2' ] ];
$array2 = [ 'id' => [ 1,2,3 ], 'headline' => [ 'test 1','test 2','test 3' ] ];

$result = array();
foreach( $array1['id'] as $val )
{
    $key = array_search( $val, $array2['id'] );
    $result['id'][]       = $array2['id'][$key];
    $result['headline'][] = $array2['headline'][$key];
}
$array2 = $result;

print_r( $array2 );

Output: 输出:

Array
(
    [id] => Array
        (
            [0] => 1
            [1] => 3
            [2] => 2
        )
    [headline] => Array
        (
            [0] => test 1
            [1] => test 3
            [2] => test 2
        )
)

I execute a foreach loop through criterion 'id' array, find each value in array to be sorted, retrieve its key and use it to add values to resulting array. 我通过标准'id'数组执行一个foreach循环,找到要排序的数组中的每个值,检索其键并将其用于将值添加到结果数组中。

Not so proud of this solution, but this is. 并非为此解决方案感到骄傲,但这是。

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

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