Ankit Doshi
Ankit Doshi

Reputation: 1174

array's key match with another array php

Ex :

First array:

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

Second array:

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

Required OUTPUT :

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

here we can see that value of first array ADDRESS,ADDRESS1 doesn't exist in array 2 key, so i need value to be set null for ADDRESS,ADDRESS1 and unnecessary field of array 2 is city which key doesn't exist in first array values is need to be unset from result array

CODE :

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

CURRENT OUTPUT OF NEW ARRAY :

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

but this is long process.as well as performance also matter. i want whole code reconstruct which i have made and just get output which is required output

Here some more need help need i want same sequence of key of output array same as first array value

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

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

Thanks in advance

Upvotes: 1

Views: 554

Answers (3)

Hüseyin BABAL
Hüseyin BABAL

Reputation: 15550

You can use following;

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

Here is working demo: Demo

Upvotes: 0

dikesh
dikesh

Reputation: 3125

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

Upvotes: 0

hsz
hsz

Reputation: 152206

Just try with:

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


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

Output:

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

Upvotes: 2

Related Questions