简体   繁体   English

如何从PHP中的键=>“值的数组”数组变为“键=>值”的数组数组

[英]How do I go from an array of key => “array of values” to an array of an array of “key => values” in php

Hah, I had no idea how else to phrase that. ah,我不知道该怎么说。 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'
);

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: 假设此数据最初来自HTML表单,则可以在此位置修复数据:

<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. 然后它将以正确的格式到达您的服务器。

This would iterate through the array with 2 foreach loops. 这将使用2个foreach循环遍历数组。 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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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