PHP将数组格式化为新数组

时间:2018-12-18 17:21:13

标签: php arrays foreach mapping

大家好,我是PHP的初学者,希望以最佳的方式转换此数组:

$old = array(
    20 =>
        array(
            'name' => 'Heels',
            'path' => '1/2/10/15/20',
        ),
    15 =>
        array(
            'name' => 'Sandals',
            'path' => '1/2/80/96/15',
        ),
    10 =>
        array(
            'name' => 'Trainers',
            'path' => '1/2/80/96/10',
        ),
);

对此:

$new = array(
    20 =>
        array(
            'value' => 20,
            'label' => 'Trainers > Sandals > Heels',
        ),
);

肯定会有大量的记录爆炸路径,并用id映射它们会降低性能,只是想知道是否有更有效的方法(如果可能),谢谢。

3 个答案:

答案 0 :(得分:3)

如果我理解正确,那么您正在尝试获取与每个类别相关的最新路径,并将其输出为面包屑。

您可以先对键(id)进行排序,然后遍历整个数组以创建面包屑。

arsort($paths); # This gives the desired output in OP but makes more sense to use krsort() to sort DESC not ASC

$breadcrumb = (object) array (
    'value' => array_keys($paths)[count($paths) - 1], # Get the highest id - if using krsort() use array_keys($paths)[0]
    'labels' => implode(' > ', array_column($paths, 'name'));
);

# Update derived from The fourth bird's answer which skips the need for the foreach().
# Concept is to build an array of the labels to then make look pretty with the > effect

这里是demo

  

输出:

object (stdClass) (2) {
    ["value"] => int(20)
    ["labels"] => string(26) "Trainers > Sandals > Heels"
}

答案 1 :(得分:1)

另一个选择可能是首先创建键和名称的映射器。然后,您可以从映射器中获取密钥以创建路径:

$result = [];
$mapper = array_combine(array_keys($old), array_column($old, 'name'));
foreach ($old as $key => $value) {
    $path = implode(' > ', array_map(function($x) use ($mapper) {
        return $mapper[(int)$x];
    }, explode('/', $value['path'])));

    $result[$key] = ['value' => $key,'label' => $path];
}

print_r($result);

Php demo

答案 2 :(得分:0)

这是硬编码方式,但我认为您需要提供更多信息才能获得动态解决方案。

<?php

$old = array(
    20 =>
        array(
            'name' => 'Heels',
            'path' => '1/2/10/15/20',
        ),
    15 =>
        array(
            'name' => 'Sandals',
            'path' => '1/2/80/96/15',
        ),
    10 =>
        array(
            'name' => 'Trainers',
            'path' => '1/2/80/96/10',
        ),
);


ksort($old);
$breadcrumbs = [];
$currentKey = 0;

foreach ( $old as $itemKey => $item) {
    $currentKey = $itemKey;
    $breadcrumbs[] = $item;

}
$new = [$currentKey] = [
    'value' => $currentKey,
    'label' => implode(' > ', $breadcrumbs)
];

printf($new);