0

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

3

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)];
}
Sign up to request clarification or add additional context in comments.

2 Comments

I have to do some calculation to each date so shorten one might not work . I need to sum the value
That is why I left the original code there, sometimes things aren't as simple as the code posted in the question.
0

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);
    }

1 Comment

$date isn't in the format of the data they are asking for.
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.