0

I have changed a for-loop into a foreach loop with array_combine for using two arrays in this foreach.

Unfortunately it look like array_combine will just get only unique value, but I need to combine all parts of value-groups like:

example:

$number = array (1,2,3,4,5,6);   
//$array = array ('a','a','b','c','d','e');   

 $array2=   array ( 
            array ('a','a','b','c','d','e'),
            array ('a','a','b','c','d','e')
                 );     

foreach (array_combine($array[0], $number) as $array2 => $number2)  {

    echo $number2 . $array2 . "<br>";
}

desired output

1a  (this result is missing)
2a
3b
4c
5d
6e

Edit: One of my $array should be a 2-dimensional array

2 Answers 2

1

This is, because you use $array as keys of your combined array and each key has to be unique, so the last one with the same key will be in your array. The other ones, will get deleted (Simple example to reproduce).

To solve your problem you could use array_map() and pass both arrays as arguments to loop through them:

array_map(function($v1, $v2){
    echo $v1 . $v2 . "<br>";
}, $number, $array);

output:

1a
2a
3b
4c
5d
6e

Demo

Sign up to request clarification or add additional context in comments.

8 Comments

Correct amp top map
@splash58 Thank you for your demo. I think I have another problem, because in my real code $array is a 2-dimensional array. I have tried to use this system and I think because of the [1] it don't worked. my old code and with array_map: eval.in/376545
@Grischa Then add your real array structure to your question
@splash58 Ok, sorry I didn't know this would be such a difference.
@Grischa Then just change the last codeline of my code in my answer from: }, $number, $array); to: }, $number, $array[0]);
|
1

You can't duplicate keys in an array, but you can simulate duplicate keys with Generators if you're running PHP > 5.5.0

$number = array (1,2,3,4,5,6);   
$array = array ('a','a','b','c','d','e');   

function myCombinedArray($keys, $values) {
    foreach($values as $index => $value) {
        yield $keys[$index] => $value;
    }
}

foreach (myCombinedArray($array, $number) as $array2 => $number2)  {

    echo $number2 . $array2 . "<br>";
}

1 Comment

Thank you. Unfortunately my hoster changed only from PHP 5.3 to 5.4. some months ago. Did you see my Edit on the question? (One of my $array should be a 2-dimensional array)

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.