array与另一个数组php的键匹配

时间:2014-04-14 08:32:15

标签: php arrays

前:

第一个阵列:

Array
(
    [0] => id
    [1] => ADDRESS
    [2] => ADDRESS1
    [3] => name
)

第二阵列:

Array
(
    [id] => 1
    [name] => Ankit
    [city] => SURAT
)

必需的输出:

    [id] => 1
    [ADDRESS]=>
    [ADDRESS1]=>
    [name] => Ankit

这里我们可以看到第一个数组ADDRESS的值,ADDRESS1在数组2键中不存在, 所以我需要为ADDRESS设置值 null ,ADDRESS1和数组2的不必要字段是 city 第一个数组值中不存在哪个键需要取消设置结果数组

代码:

    $field_arr= array('0'=>"id",
        "1"=>"ADDRESS",
        "2"=>"ADDRESS1",
        '3'=>"name",
        );
    $arr=array("id"=>"1",
        'name'=>"Ankit",
        "city"=>"Ahmedabad");
    $matching_fields =(array_diff_key(array_flip($field_arr),(array_intersect_key($arr,array_flip($field_arr)))));
    if(!empty($matching_fields)){
        foreach($matching_fields as $key=>$value){
            $new_arr[$key]=null;
        }
    }
    print_r($new_arr);
    exit;

新阵列的当前输出:

Array
(
    [ADDRESS] => 
    [ADDRESS1] => 
)

但这是一个漫长的过程。而且性能也很重要。我想要完整的代码重建我已经做了,只需要输出所需的输出

这里有一些需要帮助我需要输出数组的相同序列的键与第一个数组值相同

 my required output  :
        [id] => 1
        [ADDRESS]=>
        [ADDRESS1]=>
        [name] => Ankit

current output :
        [id] => 1
        [name] => Ankit
        [ADDRESS]=>
        [ADDRESS1]=>

提前致谢

3 个答案:

答案 0 :(得分:2)

试试:

$keys = array('id', 'name', 'ADDRESS', 'ADDRESS1');
$data = array(
  'id'   => 1,
  'name' => 'Ankit',
  'city' => 'SURAT',
);


$output = $data + array_fill_keys($keys, null);

输出:

array (size=5)
  'id' => int 1
  'name' => string 'Ankit' (length=5)
  'city' => string 'SURAT' (length=5)
  'ADDRESS' => null
  'ADDRESS1' => null

答案 1 :(得分:0)

您可以使用以下内容;

$first = array(
    "id",
    "name",
    "ADDRESS",
    "ADDRESS1"
);

$second = array(
    "id" => "1",
    "name" => "Ankit",
    "city" => "SURAT"
);

foreach ($first as $key) {
    if ($second[$key] == null) {
        $second[$key] = null;
    }
}

var_dump($second);

以下是工作演示: Demo

答案 2 :(得分:0)

$keys = array_unique(array_merge($field_arr, array_keys($arr)));
$new_array = array();

foreach ($keys as $key)
{
    $new_array[$key] = isset($arr[$key]) ? $arr[$key] : '';
}
echo "<pre>";
print_r($new_array);