Jump to content

Two arrays in to one


johnhb

Recommended Posts

I am trying to combine two arrays into one array. Have tried array_combine, array_merge but these procedures remove duplicates.

 

I have the following code:

while ($array = mysql_fetch_array($query, MYSQL_NUM))

{

$data1[] = $array[0];  eg 0=> 0.40, 1=> 0.50, 2=>0.90, 3=>0.50

$data2[] = $array[1];  eg 0=>'Fred', 1=>'Mary', 2=>'John', 3=>'Jill'

}

 

What I am trying to do is end up with the values of $data1 as the keys and the values of $data2 as the values of a new array, so I have an array like :-

0.40=>'Fred', 0.50=>'Mary', 0.90=>'John', 0.50=>'Jill'

 

Hope someone who has a better knowledge of using arrays can help or point me in the right direction.

Link to comment
https://forums.phpfreaks.com/topic/95884-two-arrays-in-to-one/
Share on other sites

Thanks kenrbnsn

This is what I now get with your code:

Array

(

    [0.4900] => Fred

    [3.0000] => John

    [0.5000] => Fred

    [0.6000] => Fred

    [2.0000] => Mary

)

 

However the array should have 8 entries. It looks like the duplicate entries have been removed.

 

Link to comment
https://forums.phpfreaks.com/topic/95884-two-arrays-in-to-one/#findComment-490922
Share on other sites

You can't have two indexes that are the same in an array. You can try doing this instead:

<?php
$data = array();
while ($array = mysql_fetch_array($query, MYSQL_NUM))
     if (!array_key_exists($array[0],$data))
            $data[$array[0]] = $array[1];
     else {
            $tmp = explode('`',$data[$array[0]]);
            $tmp[] = $array[1];
            $data[$array[0]] = implode('`',$tmp);
    }
echo '<pre>' . print_r($data,true) . '</pre>'; // debug -- show what you've stored
?>

This will put a CSV type string into the array if the key has already been used.

 

Ken

Link to comment
https://forums.phpfreaks.com/topic/95884-two-arrays-in-to-one/#findComment-490955
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.