简体   繁体   中英

Fill array with zero values in a a given range

I am working on laravel 5.3 and Here is my code

$arrayData = array();
foreach ($stats as $key => $row) {
      $arrayData[] = array(
      'number'   => $row->no,
      'level'    => $row->total_sent,
      'past'     => $row->past,
  );
}

if i dd($arrayData) its output is as

array:3 [▼
  0 => array:3 [▼
    "no" => "4"
    "level" => 3
    "past" => "3"
  ]
  1 => array:3 [▼
    "no" => "6"
    "level" => 3
    "past" => "3"
  ]
  2 => array:3 [▼
    "no" => "9"
    "level" => 3
    "past" => "3"
  ]
]

Here in above no are 4,6,9 respectively. I want final out output should contain complete data. If no exits that's fine other wise numbers should be with zero.

In above case, desired output is as at missing position there will be a correct number with zero values

array:11 [▼
  0 => array:3 [▼
    "no" => "0"
    "level" => 0
    "past" => "0"
  ]
  1 => array:3 [▼
    "no" => "1"
    "level" => 0
    "past" => "0"
  ]
  2 => array:3 [▼
    "no" => "2"
    "level" => 0
    "past" => "0"
  ]
  3 => array:3 [▼
    "no" => "3"
    "level" => 0
    "past" => "0"
  ]
  4 => array:3 [▼
    "no" => "4"
    "level" => 3
    "past" => "3"
  ]
  5 => array:3 [▼
    "no" => "5"
    "level" => 0
    "past" => "0"
  ]
  6 => array:3 [▼
    "no" => "6"
    "level" => 3
    "past" => "3"
  ]
  7 => array:3 [▼
    "no" => "7"
    "level" => 0
    "past" => "0"
  ]
  8 => array:3 [▼
    "no" => "8"
    "level" => 0
    "past" => "0"
  ]
  9 => array:3 [▼
    "no" => "9"
    "level" => 3
    "past" => "3"
  ]
  10 => array:3 [▼
    "no" => "10"
    "level" => 0
    "past" => "0"
  ]

Hope Question is clear

Thanks in advance

Initiate array with zero-filled values:

for ($i=0; $i <= 10; $i++) {
    $arrayData[$i] = [
        "no" => "$i",
        "level" => 0,
        "past" => "0",
    ];
}
foreach ($stats as $key => $row) {
    $arrayData[$row->no] = [
        'no' => $row->no,
        'level' => $row->total_sent,
        'past' => $row->past,
    ];
}

If you do not know max no value, you need to get it. Then fill $arrayData with zero elements using array_fill function

$stats = collect($stats);
$arrayData = [];

$maxNo = $stats->max('no');

$arrayData = array_fill(0, $maxNo, [
    'number' => 0,
    'level' => 0,
    'past' => 0
]);

$stats->each(function($row) use(&$arrayData){
    $arrayData[$row->no] = [
        'number'   => $row->no,
        'level'    => $row->total_sent,
        'past'     => $row->past,
    ];
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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