PHP中的度假村数组

时间:2018-03-28 16:17:53

标签: php arrays sorting

我试图创建一个对这种形式的数组进行排序的函数(最初使用动态值):

Array
(
    [0] => product_cat-24
    [1] => style_cat-97
    [2] => style_cat-98
    [3] => stone_count_cat-110
    [4] => style_cat-100
    [5] => style_cat-104
    [6] => stone_count_cat-109
    [7] => stone_count_cat-111
)

所以它看起来像这样:

Array(
    'product_cat'       => array( 24 ),
    'style_cat'         => array( 97, 98, 100, 104 ),
    'stone_count_cat'   => array( 110, 109, 111 )
);

唯一重要的是将号码分配给正确的密钥。

寻找实现这一目标必须优雅的方法。

谢谢! :)

2 个答案:

答案 0 :(得分:2)

只需使用PHP的explode()list()尝试这样做。

<?php
$array  = array
    (
    'product_cat-24',
    'style_cat-97',
    'style_cat-98',
    'stone_count_cat-110',
    'style_cat-100',
    'style_cat-104',
    'stone_count_cat-109',
    'stone_count_cat-111'
);

$new = array();
foreach($array as $val) {
    list($key, $value) = explode('-', $val);
    $new[$key][] = $value;
}

print '<pre>';
print_r($new);
print '<pre>';
?>

<强>输出:

Array
(
    [product_cat] => Array
        (
            [0] => 24
        )

    [style_cat] => Array
        (
            [0] => 97
            [1] => 98
            [2] => 100
            [3] => 104
        )

    [stone_count_cat] => Array
        (
            [0] => 110
            [1] => 109
            [2] => 111
        )

)

DEMO: https://eval.in/980195

答案 1 :(得分:1)

你也可以这样做:

$new = array();
foreach( $array as $val) {
    $tmp = explode('-', $val);
    $new[$tmp[0]][] = $tmp[1];
}