在PHP中转换关联数组

时间:2017-03-23 06:34:41

标签: php

我正在循环中获取数组。

Array
(
     [name] => Birthday
 )

Array
(
    [name] => Marriage Anniversary
)

现在我想以下列格式制作动态。我该怎么做?

return [['value' => 'birthday1', 'label' => __('Birthday1')], ['value' => 'wedding_anniversary', 'label' => __('Marriage Anniversery')]];

1 个答案:

答案 0 :(得分:0)

这可能是一种方法:

<?php
$input = [
    ['name' => 'Birthday'],
    ['name' => 'Marriage Anniversary']
];
$output = [];
array_walk($input, function($set) use (&$output) {
    $entry = $set['name'];
    $value = preg_replace('/\s+/', '_', strtolower($entry));
    $label = $entry;
    $output[] = [
        'value' => $value,
        'label' => $label
    ];
});
print_r($output);

上述代码的输出显然是:

Array
(
    [0] => Array
        (
            [value] => birthday
            [label] => Birthday
        )

    [1] => Array
        (
            [value] => marriage_anniversary
            [label] => Marriage Anniversary
        )

)

你的问题有点不清楚你建议跟踪其中一个值(“birthday1”)...如果真的需要某种计数器来表示值的出现,那么这里是上述代码的修改版本:

<?php
$input = [
    ['name' => 'Birthday'],
    ['name' => 'Marriage Anniversary'],
    ['name' => 'Birthday']
];
$output = [];
$catalog = [];
array_walk($input, function($set) use (&$catalog, &$output) {
    $entry = $set['name'];
    $value = preg_replace('/\s+/', '_', strtolower($entry));
    $catalog[$value] = isset($catalog[$value]) ? ++$catalog[$value] : 1;

    $label = $entry;
    $output[] = [
        'value' => $value . $catalog[$value],
        'label' => $label
    ];
});
print_r($output);

修改后的输出显然是:

Array
(
    [0] => Array
        (
            [value] => birthday1
            [label] => Birthday
        )

    [1] => Array
        (
            [value] => marriage_anniversary1
            [label] => Marriage Anniversary
        )

    [2] => Array
        (
            [value] => birthday2
            [label] => Birthday
        )

)