PHP在多维数组中推送简单数组值不起作用

问题描述 投票:-1回答:1

我有2个数组:

$numbers = array(0,3,8);

$data = array('January' => array('BATH' => array('ID', 'user', 'type'), 'KITCHEN' => array('ID', 'user', 'type')), 'february' => array('BATH' => array('ID', 'user', 'type'), 'KITCHEN' => array('ID', 'user', 'type')), 'march' => array('BATH' => array('ID', 'user', 'type'), 'KITCHEN' => array('ID', 'user', 'type')));

预期的输出必须是:

array (size=6)
  'January' => 
    array (size=2)
      'BATH' => 
        array (size=3)
          0 => string 'ID' (length=2)
          1 => string 'user' (length=4)
          2 => string 'type' (length=4)
      'KITCHEN' => 
        array (size=3)
          0 => string 'ID' (length=2)
          1 => string 'user' (length=4)
          2 => string 'type' (length=4)
      '0' => int '0' // // This is the first value from first array
  'february' => 
    array (size=2)
      'BATH' => 
        array (size=3)
          0 => string 'ID' (length=2)
          1 => string 'user' (length=4)
          2 => string 'type' (length=4)
      'KITCHEN' => 
        array (size=3)
          0 => string 'ID' (length=2)
          1 => string 'user' (length=4)
          2 => string 'type' (length=4)
       '0' => int '3' // This is the second value from first array
  'march' => 
    array (size=2)
      'BATH' => 
        array (size=3)
          0 => string 'ID' (length=2)
          1 => string 'user' (length=4)
          2 => string 'type' (length=4)
      'KITCHEN' => 
        array (size=3)
          0 => string 'ID' (length=2)
          1 => string 'user' (length=4)
          2 => string 'type' (length=4)
       '0' => int '8' // This is the last value from first array

我的PHP代码是:

for ($i = 0; $i < count($numbers); $i++) 
{
    foreach ($data as $key => $value) 
    {
        array_push($data[$key][$i], $numbers[$i]);
    }
}

我不知道为什么,但是当我尝试将第一个数组推到第二个数组时出现错误。 var_dump($data)返回错误:

Warning: array_push() expects parameter 1 to be array, null given in C:\wamp64\www\views\test.php on line 15

在此网站或Google上找不到答案。无法弄清楚我在做什么错。

php arrays multidimensional-array array-push
1个回答
-1
投票

您首先是循环编号,然后是数据集。我认为最好反过来做。循环遍历数据集,只要找到KITCHEN键,就从$numbers中添加一个数字,然后进行下一个数字。

<?php

$ptr = 0;
$key_to_search = 'KITCHEN';

foreach($data as $month => &$value){
    foreach($value as $key => $columns){
        if($key == $key_to_search){
            $value[$key][] = $numbers[$ptr++];
            break;
        }
    }
}

Demo: https://3v4l.org/uXACO

© www.soinside.com 2019 - 2024. All rights reserved.