使用替换值的平面数组替换二维数组中的列值

问题描述 投票:0回答:2

我有一个这种格式的二维数组:

$oldArr = [
    0 => [
        "color" => "red",
        "shape" => "circle",
        "size" => "small",
    ],
    1 => [
        "color" => "green",
        "shape" => "square",
        "size" => "large",
    ],
    2 => [
        "color" => "yellow",
        "shape" => "triangle",
        "size" => "large",
    ],
];

以及这种格式的一维数组:

$newVals = [
    0 => "large",
    1 => "large",
    2 => "small",
];

我正在尝试使用

str_replace()
遍历
"size"
中的每个
$oldArr
值,并将其替换为
$newVals
中与其位置匹配的值。由于这些数组将始终具有相同数量的顶级键值对,因此我基本上是在尝试采用
$newVals
并将其映射到每个
$oldArr["size"]
值。最后的结果应该是

$newArr = [
    0 => [
        "color" => "red",
        "shape" => "circle",
        "size" => "large",
    ],
    1 => [
        "color" => "green",
        "shape" => "square",
        "size" => "large",
    ],
    2 => [
        "color" => "yellow",
        "shape" => "triangle",
        "size" => "small",
    ],
];

任何人都可以推荐最好的方法吗?我在 foreach 循环中尝试了

str_replace
,但没有成功:

foreach($oldArr as $entity):

    str_replace($entity['size'], $newVals, $entity);

endforeach;
php arrays multidimensional-array replace mapping
2个回答
1
投票

您可以使用

array_map()
并一次循环遍历两个数组,而不是使用原始数组的大小值,您只需使用新数组,例如

$result = array_map(function($old, $new){
    return ["color" => $old["color"], "shape" => $old["shape"], "size" => $new];
}, $oldArr, $newVals);

1
投票

您可以使用此代码:

<?php

$oldArr = [
    0 => [
        "color" => "red",
        "shape" => "circle",
        "size" => "small",
    ],
    1 => [
        "color" => "green",
        "shape" => "square",
        "size" => "large",
    ],
    2 => [
        "color" => "yellow",
        "shape" => "triangle",
        "size" => "large",
    ],
];


$newVals = [
    0 => "large",
    1 => "large",
    2 => "small",
];

$newArr = array();
foreach($oldArr as $key => $entity){
    $newEntity = $entity;
    $newEntity['size'] = $newVals[$key];
    $newArr[$key] = $newEntity;
}

var_dump($newArr);
© www.soinside.com 2019 - 2024. All rights reserved.