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 can see value of first array address,address1 doesn't exist in array 2 key, need value set null address,address1 , unnecessary field of array 2 city key doesn't exist in first array values need unset 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 $key=>$value){ $new_arr[$key]=null; } } print_r($new_arr); exit;
current output of new array :
array ( [address] => [address1] => )
but long process.as performance matter. want whole code reconstruct have made , output required output
here more need need want same sequence of key of output array same first array value
required output : [id] => 1 [address]=> [address1]=> [name] => ankit current output : [id] => 1 [name] => ankit [address]=> [address1]=>
thanks in advance
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
Comments
Post a Comment