PHP多维数组按其他数组的列排序

时间:2018-09-17 11:33:01

标签: php arrays sorting

我有第一组ID:

$ids = [10,12,8];

我有数据数组:

$arr = [
        12=>[
            'content'=>'test1'
        ],
        10=>[
            'content'=>'test2'
        ],
        8=>[
            'content'=>'test3'
        ]
    ];

如何通过$arr值对数组$ids进行排序,因此结果需要:

 $arr = [
        10=>[
            'content'=>'test2'
        ],
        12=>[
            'content'=>'test1'
        ],
        8=>[
            'content'=>'test3'
        ]
    ];

1 个答案:

答案 0 :(得分:0)

<?php
$ids = [10,12,8];
$arr = [
    "12" => ['content' => 'test1'],
    "10" => ['content' => 'test2'],
    "8" => ['content' => 'test3']
];
$result = array();
foreach($ids as $key){
    if(array_key_exists($key,$arr)){
        $result[$key] = $arr[$key];
    }
}
print_r($result);
?>

快乐编码