Push second array inside first array

Asked by At

I have two array containing some value.

$type = array("first", "second", "third");

$date = array(
          0 => "2019-04-30",
          1 => "2019-05-01",
          2 => "2019-05-02",
          3 => "2019-05-03"
        );

I need output something like this:

[
    type :first, 
    date: [
        "2019-04-30": 1.2,
        .....
    ]

]

But for some reason I am not getting in that format.

This is the code I have tried.

$newArr = array();

foreach($type as $tt) {
    $newArr[]['type'] = $tt;
    $newDate = array();
    foreach ($date as $d) {
        $newDate[$d] = 1.2;
    }
    $newArr[]['date'] = $newDate;
}

Can anybody show what I did mistake.

Thank You.

3 Answers

3
Nigel Ren On Best Solutions

It just comes down to building the array and then adding it in the right order, this builds all of the data and adds it in one go at the end of the loop...

$newArr = array();

foreach($type as $tt) {
    $newDate = array();
    foreach ($date as $d) {
        $newDate[$d] = 1.2;
    }
    $newArr[] = [ 'type' => $tt, 'date' => $newDate];
}

You could shorten it to this, but it doesn't really make much difference...

foreach($type as $tt) {
    $newArr[] = [ 'type' => $tt, 'date' => array_fill_keys($date, 1.2)];
}
0
Varun Malhotra On

Lets make it more simple

$newArr = array();
$newdates = array();
  foreach($dates as $date){
  $newdates[$date] = 1.2;
}

    foreach($type as $tt) {
        $newArry[] = array("type"=>$tt,"date"=>$newdates);
    }
0
Rakesh Kumar Jakhar On

You can use array_map and array_fill_keys for the desired result

 $type = ["first", "second", "third"];
 $date = [
      0 => "2019-04-30",
      1 => "2019-05-01",
      2 => "2019-05-02",
      3 => "2019-05-03"
    ];
$newArr = [];
array_map(function($t, $d) use ($date, &$newArr){
  $newArr[] = [
    'type' => $t,
    'date' => array_fill_keys($date, 1.2)
  ];
}, $type, $date);