在PHP中修改多维数组,将键替换为值

时间:2016-05-29 02:45:03

标签: php arrays multidimensional-array foreach

如何通过将键替换为值来仅使用foreach循环来修改以下代码?例如,沙拉,鸡肉和煎饼键就是价值。

$meals = array(
    'Lunch' => array(
            'salad' => 'italian',
            'salad2' => 'ranch',
            'salad3' => 'sesame',
            'salad4' => 'bluecheese'
        ), 

    'Dinner' => array(
            'chicken' => 'grilled',
            'chicken2' => 'baked',
            'chicken3' => 'steamed',
            'chicken4' => 'fried',
            'chicken5' => 'broiled'
        ), 

    'Breakfast' => array(
        'pancakes' => 'blueberry',
        'pancakes2' => 'cherry',
        'pancakes3' => 'strawberry',
        'pancakes4' => 'lemon'
        )
);

$newkey = array();

foreach($meals as $key => $value) {
    unset($value);
    // foreach ($)...
}


print_r($meals);

4 个答案:

答案 0 :(得分:1)

修改

如果你不能使用array_flip(),那么你需要做两个循环:每餐一个,每餐一个。

示例:

foreach ($meals as $meal => $mealOptions)
{
    $revisedMealOptions = array();

    foreach ($mealOptions as $originalKey => $newKey)
    {
        $revisedMealOptions[$newKey] = $originalKey;
    }

    $meals[$meal] = $revisedMealOptions;
}

原始答案

你所追求的并不完全清楚。如果你想要的只是转向:

'Lunch' => array(
    'salad' => 'italian'
);

'Lunch' => array(
    'italian' => 'salad'
);

使用 array_flip()

示例:

$meals['Lunch'] = array_flip($meals['Lunch']);

请参阅http://php.net/manual/en/function.array-flip.php

答案 1 :(得分:0)

抱歉,我是初学者。我需要使用嵌套的$ foreach循环来解决这个问题。对于I类,不允许使用array_flip函数。我试过了

$newkey = array();

foreach($meals as $key => $value) {
  $newkey[] = $value; 
     foreach ($value as ){
    }
  }

答案 2 :(得分:0)

所以,它会读到:

基本上我需要它阅读:

阵列(

[Lunch] => array(
        [italian] => salad,
        [ranch] => salad2,
        [sesame] => salad3,
        [bluecheese] => salad4
    )
 )

答案 3 :(得分:0)

最简单的方法就是这样:

$meals = array(
    'Lunch' => array(
        'salad' => 'italian',
        'salad2' => 'ranch',
        'salad3' => 'sesame',
        'salad4' => 'bluecheese'
    ),

    'Dinner' => array(
        'chicken' => 'grilled',
        'chicken2' => 'baked',
        'chicken3' => 'steamed',
        'chicken4' => 'fried',
        'chicken5' => 'broiled'
    ),

    'Breakfast' => array(
        'pancakes' => 'blueberry',
        'pancakes2' => 'cherry',
        'pancakes3' => 'strawberry',
        'pancakes4' => 'lemon'
    )
);

$newArray = array();

foreach ($meals as $key => $value) {
    $temp = array();
    foreach ($value as $innerKey => $innerValue) {
        $temp[$innerValue] = $innerKey;
    }
    $newArray[$key] = $temp;
}

unset($meals);

基本上,您创建一个新数组并使用数组$meals从头开始构建它。