-1

Hah, I had no idea how else to phrase that. I'm trying to reformat a set of three arrays generated by form field inputs, into something that better matches my models, so I can save the values to the db.

Not sure if the solution should be some array manipulation or that I should change the "name" attribute in my form fields.

currently I have an array of my input data:

array(
  'image_id' => 
    array
      0 => '454' (length=3),
      1 => '455' (length=3),
      2 => '456' (length=3)
  'title' => 
    array
      0 => 'title1' (length=6),
      1 => 'title2' (length=0),
      2 => '' (length=6)
  'caption' => 
    array
      0 => 'caption1' (length=8),
      1 => '' (length=8),
      2 => 'caption3' (length=8)
);

and would like to change it to something like, so I can iterate over and save each array of values to the corresponding resource in my db.

array(
    0 =>
        array
        'image_id'  => '454',
        'title'     => 'title1',
        'caption'   => 'caption1'
    1 =>
        array
        'image_id'  => '455',
        'title'     => 'title2',
        'caption'   => ''
    2 =>
        array
        'image_id'  => '456',
        'title'     => '',
        'caption'   => 'caption3'
);
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
djversus
  • 13
  • 4

2 Answers2

1

This'll do it:

$array = call_user_func_array('array_map', array_merge(
    [function () use ($array) { return array_combine(array_keys($array), func_get_args()); }],
    $array
));

Assuming though that this data is originally coming from an HTML form, you can fix the data right there already:

<input name="data[0][image_id]">
<input name="data[0][title]">
<input name="data[0][caption]">

<input name="data[1][image_id]">
<input name="data[1][title]">
<input name="data[1][caption]">

Then it will get to your server in the correct format already.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • hmm if I do this I just get one big ol array with key "data" and the values all in one level: `0 => 454 1 => title1 2 => caption 1 3 => 455 4 => title2` etc. – djversus Dec 09 '14 at 01:52
1

This would iterate through the array with 2 foreach loops. They would use each other's key to construct the new array, so it would work in any case:

$data = array(
    'image_id' => array(454, 455, 456),
    'title' => array('title1', 'title2', ''),
    'caption' => array('caption1', '', 'caption3')
);

$result = array();
foreach($data as $key => $value) {
    foreach ($value as $k => $v) {
        $result[$k][$key] = $v;
    }
}
Tibor B.
  • 1,680
  • 1
  • 10
  • 12