Forum Moderators: coopster

Message Too Old, No Replies

Combining arrays

         

stratocu

3:04 pm on Jan 19, 2012 (gmt 0)

10+ Year Member



I've been trying to solve my problem for hours/days now and I am still unable to solve it. Yes, I am a beginner, but I still hope someone will help me.



<?php

// ------------------------------------//
// $link = array(id, description, url);//
// ------------------------------------//


$nr_items = 3;

$link1 = array("id1","description1","url1");
$link1 = array("id2","description2","url1");
$link1 = array("id3","description3","url3");

for( $n = 1; $n <= ($nr_items); $n++ ) {
$a=$a."\$link".$n."[0] ";
$b=$b."\$link".$n."[1] ";
$c=$c."\$link".$n."[2] ";
}


$link_id_array = explode(" ",$a);
$link_description_array = explode(" ",$b);
$link_url_array = explode(" ",$c);


print_r(array_values($link_id_array));
// array with values $link1[0] $link2[0] $link3[0]
echo "<BR>";
print_r(array_values($link_description_array));
// array with values $link1[1] $link2[1] $link3[1]
echo "<BR>";
print_r(array_values($link_url_array));
// array with values $link1[2] $link2[2] $link3[2]


?>



The result I now have when I use "print_r(array_values($link_id_array))" is "$link1[0] $link2[0] $link3[0]".
What I'd hoped to get was "id1 description url1".

Why is e.g. "$link1[0]" not 'replaced' by "id1"?
So what do I do wrong?


Thx,
John

enigma1

3:48 pm on Jan 19, 2012 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



First define the $a, $b, $c vars is not good they're used first. Then make sure the variables link1 are different because you keep overwriting them

$link1 = array("id1","description1","url1");
$link2 = array("id2","description2","url2");
$link3 = array("id3","description3","url3");

So you have 3 different vars. It is also inefficient to expand them like this you could use a multi-dimensional array to hold the data like:
$links_array = array(
array("id1","description1","url1"),
array("id2","description2","url2"),
array("id3","description3","url3"),
);

In the for loop you should use the variable as index. With your current code it could be:
$a=$b=$c='';
for( $n = 1; $n <= ($nr_items); $n++ ) {
$a = $a . ${'link' . $n}[0] . ' ';
$b = $b . ${'link' . $n}[1] . ' ';
$c = $c . ${'link' . $n}[2] . ' ';
}

stratocu

10:22 pm on Jan 19, 2012 (gmt 0)

10+ Year Member



Thanks for your quick reply (and your comments on my way of coding!).
Problem solved!


Regards,
John