PHP 用其他数组中的值替换数组索引键

标签 php arrays

<分区>

我有这两个数组,我需要用 $columns 的索引替换 $products 的数字索引。

我不知道用“foreach 循环”或另一个 PHP 函数解决它是否正确。

问题:返回的数组必须与初始数组具有相同数量的元素。

$columnas = array( "CATEGORIA", "PRODUCTO", "IMAGEN", "PRECIO", "DESCUENTO", "DISPONIBLE");
$products = array(
    array(
        "Burgers", "Doble con queso", "burger.jpg","300"
    ),
    array(
        "Burgers", "Triple", "burger_triple.jpg", "350", "10%", "si"
    ),
    array(
        "Burgers", "Triple2", "burger_triple.jpg", "380"
    ),
    array( "Burgers", "Triple3"
    ),
);

在循环中,我遍历两个数组以替换索引。

foreach( $products as $k => $product  ) {
    foreach($product as $t => $y){
        $columnsArray[$columnas[$t]] = $y;
        // $product[$columnas[$t]] = $y; // Other option
    }
    $newProducts[] = $columnsArray;
}
print_r($newProducts);

这是结果:

Array
(
    [0] => Array
        (
            [CATEGORIA] => Burgers
            [PRODUCTO] => Doble con queso
            [IMAGEN] => burger.jpg
            [PRECIO] => 300
        )

    [1] => Array
        (
            [CATEGORIA] => Burgers
            [PRODUCTO] => Triple
            [IMAGEN] => burger_triple.jpg
            [PRECIO] => 350
            [DESCUENTO] => 10%
            [DISPONIBLE] => si
        )

    [2] => Array
        (
            [CATEGORIA] => Burgers
            [PRODUCTO] => Triple2
            [IMAGEN] => burger_triple.jpg
            [PRECIO] => 380
            [DESCUENTO] => 10% <------- should not be
            [DISPONIBLE] => si <------- should not be
        )

    [3] => Array
        (
            [CATEGORIA] => Burgers
            [PRODUCTO] => Triple3
            [IMAGEN] => burger_triple.jpg <------- should not be
            [PRECIO] => 380 <------- should not be
            [DESCUENTO] => 10% <------- should not be
            [DISPONIBLE] => si <------- should not be
        )

)

最佳答案

<?php
$columnas = array( "CATEGORIA", "PRODUCTO", "IMAGEN", "PRECIO", "DESCUENTO", "DISPONIBLE");
$products = array(
    array(
        "Burgers", "Doble con queso", "burger.jpg","300"
    ),
    array(
        "Burgers", "Triple", "burger_triple.jpg", "350", "10%", "si"
    ),
    array(
        "Burgers", "Triple2", "burger_triple.jpg", "380"
    ),
    array( "Burgers", "Triple3"
    ),
);
$newProducts = [];
foreach ($products as $p) {
        // slice out the same number of keys from $columnas, combine into the new array
        $newProducts[] = array_combine(array_slice($columnas,0,count($p)),$p);
}
print_r($newProducts);

关于PHP 用其他数组中的值替换数组索引键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70501287/

相关文章:

c++ - 使用 C 或 C++ 的汇编语言

c# - 拆分并连接 C# 字符串

C程序: Strcmp

php - 更改服务器上Wordpress生成的文件的权限

php - 从 Laravel 中的 mysql 表中检索值

php - 这仍然容易受到sql攻击吗?你能看出什么问题吗?

Java 注册表类?

php - 这个登录系统足够安全吗?

Java数组: direct access to component in array

arrays - 二维数组的计数算法