简体   繁体   English

用PHP中的相同数据填充数组

[英]Fill array with same data in php

I have an array with some data that returns me from the database, the problem is that not all the keys are associated, I should fill the missing keys with data to 0. 我有一个数组,其中包含一些从数据库返回我的数据,问题是并非所有键都已关联,我应该将丢失的键中的数据填充为0。

My array is by default is: 我的数组默认是:

array:1 [▼
  9 => array:2 [▼
    4 => array:3 [▼
      "Orange" => array:3 [▼
        "price" => "600.00"
        "total" => "690.00"
      ]
      "Apple" => array:3 [▼
        "price" => "650.00"
        "total" => "870.00"
      ]
      "Banana" => array:3 [▼
        "price" => "50"
        "total" => "40"
      ]
    ]
    21 => array:1 [▼
      "Apple" => array:3 [▼
        "price" => "44"
        "total" => "33"
      ]
    ]
  ]
]

The array should have the same structure but with data at 0 数组应具有相同的结构,但数据为0

Result: 结果:

array:1 [▼
  9 => array:2 [▼
    4 => array:3 [▼
      "Orange" => array:2 [▼
        "price" => "600.00"
        "total" => "690.00"
      ]
      "Apple" => array:2 [▼
        "price" => "650.00"
        "total" => "870.00"
      ]
      "Banana" => array:2 [▼
        "price" => "50"
        "total" => "40"
      ]
    ]
    21 => array:3 [▼
      "Apple" => array:2 [▼
        "price" => "44"
        "total" => "33"
      ],
      "Orange" => array:2 [▼
        "price" => "0"
        "total" => "0"
      ],
      "Banana" => array:2 [▼
        "price" => "0"
        "total" => "0"
      ]
    ]
  ]
]

The "for" below modify each array with adding any new value and also avoid duplicate values. 下面的“ for”通过添加任何新值来修改每个数组,并避免重复值。 Basically, it finds the differences and then merge that, setting the first array to clone each array. 基本上,它找到差异,然后合并差异,设置第一个数组以克隆每个数组。

$fruits = array (
    1 => array('Manzana', 'Naranja', 'Pera'),
    2 => array('Pera', 'Sandia'),
    3 => array('Manzana', 'Melocotones')
);
print_r($fruits);





for ($i = 1; $i <= count($fruits)-1; $i++) {
    $result = array_diff($fruits[1], $fruits[1+$i]);
    $merge = array_merge($fruits[1+$i], $result);
    $fruits[1+$i] = $merge;
    $fruits[1] = $merge;
}

print_r($fruits);
?>

Here to see how run it! 在这里看看如何运行! https://repl.it/KqUi/3 https://repl.it/KqUi/3

If you will always use the first element as boilerplate you can do something like this: 如果您始终将第一个元素用作样板,则可以执行以下操作:

$boilerplate = reset($array);
array_walk_recursive($boilerplate, function (&$value) {
    $value = 0;
});

$array = array_map(function ($items) use ($boilerplate) {
    return array_merge($items, array_diff_key($boilerplate, $items));
}, $array);

Here is working demo . 这是工作演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM