johnhb Posted March 12, 2008 Share Posted March 12, 2008 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 More sharing options...
The Little Guy Posted March 13, 2008 Share Posted March 13, 2008 Try this: <?php $array = mysql_fetch_array($query, MYSQL_NUM); $data1 = array(); $data2 = array(); foreach($array as $key => $val){ $data1[] = $key; $data2[] = $val; } ?> Link to comment https://forums.phpfreaks.com/topic/95884-two-arrays-in-to-one/#findComment-490896 Share on other sites More sharing options...
kenrbnsn Posted March 13, 2008 Share Posted March 13, 2008 Try this: <?php $data = array(); while ($array = mysql_fetch_array($query, MYSQL_NUM)) $data[$array[0]] = $array[1]; echo '<pre>' . print_r($data,true) . '</pre>'; // debug -- show what you've stored ?> Ken Link to comment https://forums.phpfreaks.com/topic/95884-two-arrays-in-to-one/#findComment-490916 Share on other sites More sharing options...
johnhb Posted March 13, 2008 Author Share Posted March 13, 2008 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 More sharing options...
kenrbnsn Posted March 13, 2008 Share Posted March 13, 2008 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 More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.