在PHP中使用另一个数组排序数组的最佳方法是什么?

时间:2018-06-22 06:45:54

标签: php

假设我有一个要排序的数组,该顺序不是可计算的,而是由另一个按所需顺序列出键的数组给出的:

$ordering_array = [
    'c',
    'a',
    'k',
    'e',
];

复杂的是,并不是所有这些键都可以在我的数组中进行排序:

$given_array = [
    'a' => 'value',
    'c' => 'value',
    'e' => 'value',
];

最干净/最快的方法是什么?

我的方法是:

$new_array = array_fill_keys($ordering_array, NULL);

foreach ($given_array as $key => $value) {
  $new_array[$key] = $value;
}

$new_array = array_filter($new_array);

有更好的方法吗?

6 个答案:

答案 0 :(得分:2)

您可以将foreach替换为array_replace()

$new_array = array_fill_keys($ordering_array, NULL);
$new_array = array_replace($new_array, $given_array);
$new_array = array_filter($new_array);

答案 1 :(得分:1)

您可以尝试

 [woocommerce_product_filter] — shows a live Product Search Filter.
 [woocommerce_product_filter_attribute] — shows a live Product Attribute Filter.
 [woocommerce_product_filter_category] — shows a live Product Category Filter.
 [woocommerce_product_filter_price] — shows a live Product Price Filter.
 [woocommerce_product_filter_tag] —  shows a live Product Tag Filter.

 [product_category category="shirt"]  - Displayed `shirt` category product

答案 2 :(得分:1)

在foreach的位置使用array_merge()array_replace都有效

尝试一下:

$ordering_array = ['c', 'a', 'k', 'e'];
$given_array = ['a' => 'value', 'c' => 'value', 'e' => 'value'];

$new_array = array_fill_keys($ordering_array, NULL);

$new_array = array_merge($new_array, $given_array);
                       OR
$new_array = array_replace($new_array, $given_array);

$new_array = array_filter($new_array);

答案 3 :(得分:1)

这是一个解决它的方法:

$ordering_array = ['c', 'a', 'k', 'e'];
$given_array = ['a' => 'value', 'c' => 'value', 'e' => 'value'];
$outputArray = array_merge(array_intersect_key(array_flip($ordering_array), $given_array), $given_array);
print_r($outputArray);

@rkj很近,但这是完成的过程

在这里测试:http://sandbox.onlinephpfunctions.com/code/95b30f6e402b1afdb18867471888ff8ba38867de

答案 4 :(得分:0)

尝试使用uksort

demo

<?php 
    $ordering_array  = [
        'c',
        'a',
        'k',
        'e',
    ];
    $given_array  = [
        'a' => 'value-a',
        'c' => 'value-c',
        'e' => 'value-e',
    ];

    uksort($given_array , function ($a, $b) use ($ordering_array) {

        $pos_a = array_search($a,$ordering_array);
        $pos_b = array_search($b,$ordering_array);
        return $pos_a - $pos_b;
    });

    var_dump($given_array );

答案 5 :(得分:0)

简单明了:

<?php    
$ordering_array = [
    'c',
    'a',
    'k',
    'e',
];

$given_array = [
    'a' => 'valuea',
    'c' => 'valuec',
    'e' => 'valuee',
];

foreach($ordering_array as $K)
    if(array_key_exists($K, $given_array))
        $ordered[$K] = $given_array[$K];

var_export($ordered);

输出:

array (
  'c' => 'valuec',
  'a' => 'valuea',
  'e' => 'valuee',
)

如果数据允许,您可以用isset($given_array[$K])修剪一个或两个字节。

相关问题