user419503
user419503

Reputation: 11

array_combine empty values

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

Answers (6)

ForgottenPark
ForgottenPark

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

Alexander Rubia
Alexander Rubia

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

rubber boots
rubber boots

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

Gumbo
Gumbo

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

akonsu
akonsu

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

Piotr Müller
Piotr Müller

Reputation: 5558

$newarray = Array();
foreach( $columnarray as $key => $columnname )
{
if ( isset($secondarray[$key]) ) $newarray[$columnname] = $secondarray[$key];
}

Upvotes: 0

Related Questions