Reputation: 11
One array is 35 elements (mysql column names)
Array ( [1] => ID...)
second is only few elements:
Array ( [1] => 63 [2] => REF213211 [3] => aaa [7] => Warszawa [8] => Wola [12] => 100 [14] => 1 [15] => 100 [35] => 1 )
I need to combine first array as keys for second array
Please help
Upvotes: 1
Views: 4418
Reputation: 101
https://www.php.net/manual/en/function.array-fill-keys.php
array_fill_keys(['a', 'b', 'c'], null);
Result:
array(3) {
'a' => NULL
'b' => NULL
'c' => NULL
}
Upvotes: 0
Reputation: 66
Example:
$header = ["a", "b", "c"];
$values = array_combine($header, array_fill(0,count($header),null));
Result:
array(3) {
'a' => NULL
'b' => NULL
'c' => NULL
}
Upvotes: 4
Reputation: 15204
if the keys are identical (seems to be in your case), it's simple:
$combined_array = array_combine( array_values($array1), array_values($array2) );
if the first array has more keys than the second array, you can generate a temporary array for array1 which has only these keys that are in array2 (intersection of keys):
$temporary = array_intersect_key( $array1, $array2 );
$combined_array = array_combine( array_values($temporary), array_values($array2) );
Regards
rbo
Upvotes: 2
Reputation: 655489
You could use a simple foreach
like this:
$combined = array();
foreach ($keys as $index => $key) {
$combined[$key] = isset($values[$index]) ? $values[$index] : null;
}
This will combine the keys in $keys
with the values in $values
. If there is no corresponding value in $values
it will result in null
.
Upvotes: 2
Reputation: 29566
if you want to get a hash as the result, iterate over both arrays until the shortest array is completely traversed and put key/value pairs into the hash table.
Upvotes: 0
Reputation: 5558
$newarray = Array();
foreach( $columnarray as $key => $columnname )
{
if ( isset($secondarray[$key]) ) $newarray[$columnname] = $secondarray[$key];
}
Upvotes: 0