0

I need to create a set of arrays that look like this:

Array ([ID] => 55 [status] => u [resvdate] => 07/16/2018 [price] => 119.00 [source] => C) 
Array ([ID] => 56 [status] => u [resvdate] => 07/17/2018 [price] => 119.00 [source] => C) 
Array ([ID] => 57 [status] => u [resvdate] => 07/18/2018 [price] => 119.00 [source] => C) 

from five arrays that look like this:

Array ( [resvdate1] => 07/16/2018 [resvdate2] => 07/17/2018 [resvdate3] => 07/18/2018 ) 
Array ( [resvdateid1] => 55 [resvdateid2] => 56 [resvdateid3] => 57 ) 
Array ( [resvprice1] => 119.00 [resvprice2] => 119.00 [resvprice3] => 119.00 ) 
Array ( [pricesource1] => C [pricesource2] => C [pricesource3] => C ) 
Array ( [rowstatus1] => u [rowstatus2] => u [rowstatus3] => u )

Do I just need to loop through each array and pick off the values or is there a more elegant way to do this?

1
  • 1
    This is not valid PHP array syntax. And can you explain how the data should map from the inputs to the desired output. I would not want to assume. Commented Jul 30, 2018 at 0:28

1 Answer 1

1

Here's a go at it:

$data = [
  [
    "resvdate1" => "07/16/2018",
    "resvdate2" => "07/17/2018",
    "resvdate3" => "07/18/2018"
  ],
  [
    "resvdateid1" => 55, 
    "resvdateid2" => 56,
    "resvdateid3" => 57
  ],
  [
    "resvprice1" => "119.00",
    "resvprice2" => "119.00",
    "resvprice3" => "119.00"
  ],
  [
    "pricesource1" => "C", 
    "pricesource2" => "C", 
    "pricesource3" => "C"
  ],
  [
    "rowstatus1" => "u",
    "rowstatus2" => "u",
    "rowstatus3" => "u"
  ]
];

$keys = [
  "resvdate" => "resvdate",
  "resvdateid" => "id",
  "resvprice" => "price",
  "pricesource" => "source",
  "rowstatus" => "status"
];
$result = [];

foreach ($data as $a) {
  $i = 0;

  foreach ($a as $k => $v) {
    $result[$i++][$keys[preg_replace("/\d/", "", $k)]] = $v;
  }
}

print_r($result);

Output

Array
(
    [0] => Array
        (
            [resvdate] => 07/16/2018
            [id] => 55
            [price] => 119.00
            [source] => C
            [status] => u
        )

    [1] => Array
        (
            [resvdate] => 07/17/2018
            [id] => 56
            [price] => 119.00
            [source] => C
            [status] => u
        )

    [2] => Array
        (
            [resvdate] => 07/18/2018
            [id] => 57
            [price] => 119.00
            [source] => C
            [status] => u
        )

)

Explanation

This is basically a column to row mapping involving a little key adjustment along the way.

Sign up to request clarification or add additional context in comments.

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.