str_replace:一维替换数组,二维干草堆

时间:2016-03-08 16:43:59

标签: php arrays multidimensional-array str-replace

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

$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;

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:1)

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

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