1

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

6 Answers 6

4

Example:

$header = ["a", "b", "c"];
$values = array_combine($header, array_fill(0,count($header),null));

Result:

array(3) {
  'a' => NULL
  'b' => NULL
  'c' => NULL
}
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

2

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

Comments

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

Comments

0

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.

Comments

0

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
}

1 Comment

Please add the link to the function documentation for reference

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.