2016-03-03 76 views
1

我想几个阵列组合成一个,他们是一种形式后与未知数量的元素,如结果:PHP结合几个阵列来一个

$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中的常见问题,将单独的字段组合成单个数组。什么会是更好的解决方案?

+1

3x'temp => 500' in your output,typo? – Rizier123

回答

0

使用下面的代码: -

$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 
     ) 

) 
-1
$result[$ids]['name'] = $names[0]; 
$result[$ids]['temp'] = $temps[0] 
+3

你能解释你的答案吗? – Will

2

你可以通过你所有的3个数组的循环在与array_map()一次。在那里你可以返回新数组,每个数组的值都是3

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

尼斯答案:)你的输出改变了临时值,但OP已经将它作为第一个索引500发布到其他数组中。 –

+0

@RaviHirani由于OP的代码没有实现,他说他得到正确的输出,我认为这只是一个错字,但只是为了确保我在OP的问题下写了一条评论。 – Rizier123

+0

好的。我也强调了它。我也假设它是Typo。然后我需要改变我的答案:D –

0

如果你都OK了破坏性的解决方案,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; 
}