【问题标题】:PHP combine several arrays to onePHP 将多个数组合二为一
【发布时间】:2016-03-03 19:12:17
【问题描述】:

我想将几个数组合并为一个,它们是表单帖子的结果,其中包含未知数量的元素,例如:

$ids = [53,54,55];
$names = ['fire','water','earth'];
$temps = [500,10,5];

我想要的是制作一个函数,将这些数组作为输入并产生单个输出,例如

$elements = [['id'=>53,'name'=>'fire','temp'=>500] , ['id'=>54,'name'=>'water','temp'=>500] , ['id'=>55,'name'=>'earth','temp'=>500]]

我想出了以下解决方案:

function atg($array) {
  $result = array();
  for ($i=0;$i<count(reset($array));$i++) {
      $newAr = array();
      foreach($array as $index => $val) {
        $newAr[$index] = $array[$index][$i];
      }
      $result[]=$newAr;
  }
  return $result;
}

可以这样称呼

$elements = atg(['id' => $ids, 'name' => $names, 'temp' => $temps]);

它会产生正确的输出。对我来说,这似乎有点过于复杂,而且我确信这是 PHP 中表单帖子的一个常见问题,将单独的字段组合到每个项目的单个数组中。有什么更好的解决方案?

【问题讨论】:

  • 3x temp =&gt; 500 在你的输出中,错字了吗?

标签: php arrays multidimensional-array


【解决方案1】:

您可以使用array_map() 一次循环遍历所有 3 个数组。在那里,您可以只返回具有 3 个数组中每个数组的值的新数组,例如

$result = array_map(function($id, $name, $temp){
    return ["id" => $id, "name" => $name, "temp" => $temp];
}, $ids, $names, $temps);

【讨论】:

  • 好答案 :) 您的输出已更改临时值,但 OP 已将其作为第一个索引 500 发布到其他数组。
  • @RaviHirani 由于 OP 的代码没有实现这一点,他说他得到了正确的输出,我认为这只是问题中的一个错字,但只是为了确保我在 OP 的问题下写了评论。
  • 好的。我也强调了它。我还假设它是错字。然后我也需要改变我的答案:D
【解决方案2】:

使用下面的代码:-

$ids = [53,54,55];
$names = ['fire','water','earth'];
$temps = [500,10,5];
$result = [];
foreach($ids as $k=>$id){
  $result[$k]['id'] = $id;
  $result[$k]['name'] =$names[$k];
  $result[$k]['temp'] = $temps[0];
}
echo '<pre>'; print_r($result);

输出:-

Array
(
    [0] => Array
        (
            [id] => 53
            [name] => fire
            [temp] => 500
        )

    [1] => Array
        (
            [id] => 54
            [name] => water
            [temp] => 500
        )

    [2] => Array
        (
            [id] => 55
            [name] => earth
            [temp] => 500
        )

)

【讨论】:

    【解决方案3】:

    如果你对破坏性解决方案没意见,array_shift 可以解决问题:

    $elements = array();
    while (!empty($ids)) {
      $elements[] = array(
        'id' => array_shift($ids),
        'name' => array_shift($names),
        'temp' => array_shift($temps),
       );
    }
    

    如果你想创建一个函数,使用与你的例子相同的参数,一个解决方案可能是

    function atg($array) {
      $elements = array();
    
      while (!empty($array[0])) {
        $new_element = array();
        foreach ($array as $key_name => $array_to_shift) {
          $new_element[$key_name] = array_shit($array_to_shift);
        }
        $elements[] = $new_element;
      }
      return $elements;
    }
    

    【讨论】:

      【解决方案4】:
      $result[$ids]['name'] = $names[0];
      $result[$ids]['temp'] = $temps[0]
      

      【讨论】:

      • 你能解释一下你的答案吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-04
      • 1970-01-01
      • 2021-10-21
      • 1970-01-01
      相关资源
      最近更新 更多