katie hudson
katie hudson

Reputation: 2893

PHP Populating a multi-dimensional array

I am trying to make an array in this type of format

Array
(
    [name] => 'Nick'
    [email] => '[email protected]'
    [groups] => Array (
        [0] => 'group1'
        [1] => 'group2'
        [2] => 'group3'
    )
)

name and email will contain one value. groups will contain multiple values (different for all people).

So I am in a loop defined like so

foreach($result as $info) {

}

Now the $info variable contains a lot of data, about lots of users. To get the name and email of each user, I can do

$name = $info["name"][0];
$email = $info["email"][0];

I can then start building the array I am attempting to make

$userData = array(
    "name" => $name,
    "email" => $email
);

To get the groups, I need to do

foreach($info["group"] as $group) {
    print_r($group["name"]);    
}

My code at the moment looks like the following $userData = array();

foreach($result as $info) {

    $name = $info["disName"][0];
    $email = $info["email"][0];

    $userData = array(
        "name" => $name,
        "email" => $email
    );

    foreach($info["group"] as $group) {
        print_r($group["name"]);
    }

}

How can I get this data I am extracting into an Array in the format I need?

Thanks

Upvotes: 1

Views: 51

Answers (1)

Happy Coding
Happy Coding

Reputation: 2525

Modify your code..

foreach($result as $info) {

    $name = $info["disName"][0];
    $email = $info["email"][0];

    $userData = array(
        "name" => $name,
        "email" => $email
    );

    foreach($info["group"] as $group) {
        $groups[] = $group;
    }

    $userData['group'] = $groups;

}

$groups is an array for index $userData['group']

Upvotes: 1

Related Questions