PHP多个数组到一个关联数组

时间:2013-01-06 04:43:08

标签: php arrays merge multidimensional-array associative

如何合并这三个数组

$name ={"Tom", "John", "David"};
$v1 = {"Tom":100, "David":200};
$v2 = {"John":500, "Tom":400};

以两种不同的方式进入一个多维关联数组? 一种方法是键顺序应该与数组“name”的顺序相同。

$name_merged_original_order = array (
    "Tom" => Array(
        "v1" => 100,
        "v2" => 400
    ),
    "John" => Array(
        "v1" => "N/A",
        "v2" => 500
    ),
    "David" => Array(
        "v1" => 100,
        "v2" => "N/A"
    )
)

另一种方法是数组“name”的字母:

$name_merged_asc = array (
    "David" => Array(
        "v1" => 100,
        "v2" => "N/A"
    ),
    "John" => Array(
        "v1" => "N/A",
        "v2" => 200
    ),
    "Tom" => Array(
        "v1" => 100,
        "v2" => 400
    ),
)

棘手的部分是数组“v1”和“v2”未被命名为“name”的键。它们也没有“名称”中的所有键。谢谢!

4 个答案:

答案 0 :(得分:2)

没有经过测试和最简单的解决方案:

$name_merged_original_order = array();
foreach($name as $key){
    $name_merged_original_order[$key] = array();
    if(array_key_exists($key, $v1)){
        $name_merged_original_order[$key]['v1'] = $v1[$key];
    }
    else{
        $name_merged_original_order[$key]['v1'] = 'N/A';
    }
    if(array_key_exists($key, $v2)){
        $name_merged_original_order[$key]['v2'] = $v2[$key];
    }
    else{
        $name_merged_original_order[$key]['v2'] = 'N/A';
    }
}

sort($name);
$name_merged_asc = array();
foreach($name as $key){
    $name_merged_asc[$key] = array();
    if(array_key_exists($key, $v1)){
        $name_merged_asc[$key]['v1'] = $v1[$key];
    }
    else{
        $name_merged_asc[$key]['v1'] = 'N/A';
    }
    if(array_key_exists($key, $v2)){
        $name_merged_asc[$key]['v2'] = $v2[$key];
    }
    else{
        $name_merged_asc[$key]['v2'] = 'N/A';
    }
}

答案 1 :(得分:1)

据我所知,你会喜欢这样的东西:

$name = array("Tom", "John", "David");
$result = array();
$v1 = array("Tom" => "200", "John" => "100", "David" => "10");
$v2 = array("Tom" => "254", "David" => "156");
$vars = array("v1", "v2");
foreach($name as $n)
{
  $result[$n] = array();
  foreach($vars as $v)
  {
    if(array_key_exists($n, ${$v}))
      $result[$n][$v] = ${$v}[$n];
  }
}

我希望$result是您所需要的。

答案 2 :(得分:1)

例如,您有这些数组:

<?php
$FirstArrays = array('a', 'b', 'c', 'd');
$SecArrays = array('1', '2', '3', '4');

1)

foreach($FirstArrays as $index => $value) {
    echo $FirstArrays[$index].$SecArrays[$index];
    echo "<br/>";
}

或2)

for ($index = 0 ; $index < count($FirstArrays); $index ++) {
  echo $FirstArrays[$index] . $SecArrays[$index];
  echo "<br/>";
}

答案 3 :(得分:0)

从您的评论中假设您只需要在所有3个数组中匹配的项目:

for( $i=0; $i< count($name) ; $i++){
    if( !empty( $v1[ $name[$i]]) &&  !empty( $v2[ $name[$i]]) ){
       $newArray[$name[$i]]= array( 'v1'=> $v1[ $name[$i]], 'v2'=> $v2[ $name[$i]]):
    }
}

要排序:

  asort($newArray);