PHP 使用另一个数组中的键值更改数组键


PHP change array keys with key values from another array

我有 2 个数组。我正在尝试做的是将$choices数组键替换为相应的$data键

这就是我期望看到的。我希望这是有道理的

$choices = array(
    'fruits' => array(
        'Red Apple' => '',
        'Yellow Banana' => '',
        'Orange Orange' => '',
    ),
    ...
    ...
);

这是我的代码

$data = array(
    'fruits' => array(
        'apple' => 'Red Apple',
        'banana' => 'Yellow Banana',
        'orange' => 'Orange Orange',
    ),
    'vegetables' => array(
        'potato' => 'Brown Potato',
        'carrot' => 'Orange Carrot',
        'cabbage' => 'Green Cabbeage',
    ),
    'vehicles' => array(
        'car' => 'Small Car',
        'plane' => 'Large Plane',
        'train' => 'Medium Train',
    )
);
$choices = array(
    'fruits' => array(
        'apple' => 'gjhgfj',
        'banana' => 'gjfgjfg',
        'orange' => 'gfjfgjfg'
    ),
    'vegetables' => array( 
        'potato' => 'gjfgj',
        'carrot' => 'gjfgj',
        'cabbage' => 'gjfgj'
    ),
    'vehicles' => array(
        'car' => 'gjfgj',
        'plane' => 'gfjgfjfgj',
        'train' => 'gjfgjghj'
    )
);
$choice = 'fruits';
if(array_key_exists($choice, $choices)) {
    $array = $choices[$choice];
    //this is where i want to swap array keys
}

更新

根据@andrew的回答,这就是我现在所拥有的

if(array_key_exists($choice, $choices)) {
    $array = $choices[$choice];
    //this is where i want to swap array keys
    for ($i = 0; $i < count($choices); $i++) {
       $array[$i] = array_combine(array_keys($data[$i]), $array[$i]);
    }
}

可能是这样的:

foreach ($data as $key => $val){
   $choices[$key] = $val;
   array_flip($choices[$key]);
}

array_combinearray_flip将工作

已编辑,并非 100% 确定您要实现的目标,但这可能会有所帮助