简体   繁体   English

如何合并具有可变值的数组

[英]How can i merge an array with variable values

I couldn't find it on Google, or used the wrong keyword. 我在Google上找不到它,或者使用了错误的关键字。 How can i merge a variable value "[contestant variable_number -fieldname]" to a multidimensial array? 如何将变量值“ [contestant variable_number -fieldname]”合并到多维数组?

Example of the array: 数组的示例:

array (
  [contestant1-gender] => M
  [contestant1-first-name] => Wyatt
  [contestant1-last-name] => Heath
  [contestant1-occupation] => Ipsa architecto vol
  [contestant1-email] => dipuxo@mailinator.com
  [contestant1-phone] => +1 (992) 741-8123
  [contestant2-gender] => M
  [contestant2-first-name] => Leonard
  [contestant2-last-name] => Acosta
  [contestant2-occupation] => Aut sunt qui offici
  [contestant2-email] => sajomogylu@mailinator.com
  [contestant2-phone] => +1 (462) 687-8393
  [department] => In mollitia impedit
  [street] => Sed error magnam obc
  [number] => 41
  [bus] => In iste ut perspicia
  [postalcode] => Commodo impedit vol
  [city] => Ad iure veniam veli
  [country] => nl
)

To something like this: 对于这样的事情:

Array (
   [0] => contestant (
     [0] => gender ( )
     [1] => first-name ()
   )
   [1] => contestant (
     [0] => gender ( )
     [1] => first-name ()
   )
   [2] => contestant (
     [0] => gender ( )
     [1] => first-name ()
   )
)

I think this at least approximates that for which you are looking: 我认为这至少近似于您正在寻找的目标:

$array = [
   'contestant-1-gender' => 'M',
   'contestant-1-first-name' => 'Wyatt',
   'contestant-1-last-name' => 'Heath',
   'contestant-1-occupation' => 'Bl;ah blah',
   'contestant-2-gender' => 'M',
   'contestant-2-first-name' => 'Leonard',
   'contestant-2-last-name' => 'Acosta',
   'contestant-2-occupation' => 'Foo',
   'department' => 'Who cares?'
];

$contestants = [];
array_walk($array, function($val, $key) use (&$contestants) {
   if (preg_match('/contestant\-(?P<id>[\d+])\-(?P<field>.*)/', $key, $matches))
   {
      $contestants[$matches['id']][$matches['field']] = $val;
   }
});

print_r($contestants);

Output: 输出:

Array
(
    [1] => Array
        (
            [gender] => M
            [first-name] => Wyatt
            [last-name] => Heath
            [occupation] => Bl;ah blah
        )

    [2] => Array
        (
            [gender] => M
            [first-name] => Leonard
            [last-name] => Acosta
            [occupation] => Foo
        )

)

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

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