1

如何合并这三个数组

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

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

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

4 回答 4

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';
    }
}
于 2013-01-06T04:59:49.197 回答
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/>";
}
于 2013-03-28T13:00:58.613 回答
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是你需要的。

于 2013-01-06T05:06:43.993 回答
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);
于 2013-01-06T04:59:49.867 回答