LogicLooking
LogicLooking

Reputation: 928

Not understanding arrays? - creating associative from two arrays

I have two arrays that look like such:

$array_one = array('one', 'two', 'three');
$array_two = array(array('one', 'one', 'one'), array('two', 'two', 'two'), array('three', 'three', 'three'))

I then want an associative array matching each name with the array:

array(
    'one' => array('one', 'one', 'one'),
    // .... and so on
);

Problem?

I thought this would be easy to do:

some_storage = array();
foreach($array_one as $key){
    foreach($array_two as $value){
        $some_storage[$key] = $value;
    }
}

But apparently I'm failing at something because the end result is:

array(
    'one' => array('three', 'three', 'one'),
    'two' => array('three', 'three', 'three'),
    'three' => array('three', 'three', 'three'),
);

I know the fix is super duper simple - but I don't know what it is ...

Upvotes: 0

Views: 71

Answers (3)

Angry Goomba
Angry Goomba

Reputation: 470

Methinks your problem is that your nested loop runs through all values of Array Two Why not try a for loop:

for ($i = 0; $i < count($array_one); $i += 1) {
    $some_storage[$array_one[$i]] = $array_two[$i];
}

Upvotes: 0

Cobra_Fast
Cobra_Fast

Reputation: 16111

$array_result = array();
foreach ($array_one as $key => $val)
    $array_result[$val] = $array_two[$key];

Upvotes: 2

Denat Hoxha
Denat Hoxha

Reputation: 945

This looks like something that can be done with array_combine.

Upvotes: 4

Related Questions