Hey all,

I'm having a horrible time with a multidimensional array that I'm trying to create. I understand why it's creating it the way that it is, but don't know how I can fix it. If someone can assist, that would be amazing. Here's the current output:

Array
(
    [john] => Array
        (
            [0] => smith
            [1] => thompson
        )

)
Array
(
    [david] => Array
        (
            [0] => duval
            [1] => craig
            [2] => jacobs
        )

)

My desired output is:

Array
(
    [0] => Array
        (
            [john] => Array
                (
                    [0] => smith
                    [1] => thompson
                )

        )

    [1] => Array
        (
            [david] => Array
                (
                    [0] => duval
                    [1] => craig
                    [2] => jacobs
                )

        )

)

Here's a glimpse at the PHP code.

....
$first_name = array();
$last_name = array();

$q = "SELECT...";
$r = mysql_query($q);
while ($row = mysql_fetch_assoc($r)) { 
    $first_name[] = $row['first_name'];
    $last_name[] = $row['last_name'];
}

for ($x=0;$x<$count_first_name;$x++) {

..........................

	$array = array($first_name[$x]=>(explode(",",$last_name[$x])));
}

I understand that when it counts 2 first names, and $x = 0 it has to rerun the loop, resulting in creating two arrays. I've tried to create it with

$array[] = array($first_name[$x]=>(explode(",",$last_name[$x])));

But that displayed two different arrays again since the count_names = 2. This is killing me!! I'd appreciate anyone's input.

Change this line:

$array = array($first_name[$x]=>(explode(",",$last_name[$x])));

to:

$array[$x] = array($first_name[$x]=>(explode(",",$last_name[$x])));

This it should work. Remember to declare $array = array(); before the loop. Bye :)

Change this line:

$array = array($first_name[$x]=>(explode(",",$last_name[$x])));

to:

$array[$x] = array($first_name[$x]=>(explode(",",$last_name[$x])));

This it should work. Remember to declare $array = array(); before the loop. Bye :)

Thanks for your feedback Cereal, but still the same problem. It creates two arrays now. One with

Array
(
[0] => Array
(

............

)
)

The second one creates the array as I want it to look, but still creating two arrays. Any other solutions?

Ok, change it like this:

$a = array();
while($row = mysql_fetch_object($r))
{
        if(array_key_exists($row->first_name,$a) == true)
        {
                array_push($a[$row->first_name],$row->last_name);
        }
        else
        {
                $a[$row->first_name] = array($row->last_name);
        }
}
$result = array_chunk($a,1,true);
print_r($result);

bye :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.