0

I'm trying to build my first multidimensional array - which I understand ok using hardcoded values, but trying to fill the array with values is getting me tied in knots.

I've got 2 resultsets that I'm using to build the array.

  • I have a method $hostnames that returns all 'hostnames' as an object

    $hostnames = $server_model->get_hostnames();

  • I have a method $usernames that returns all 'users' of the 'hostname' that is specified above.

    $usernames = $userlogons_model->get_users_by_hostname($hostname->hostname);

First, I'm building the array:

$hostnames = array(
            $host => $hostname,
            $users => array(
                $key => $username
            )
        );

Then I am populating the arrays:

$hostnames = $server_model->get_hostnames_for_costs();

        foreach ($hostnames as $hostname) {

            $usernames = $userlogons_model->get_users_by_hostname($hostname);

            echo $hostname->hostname;

            foreach ($usernames as $user){

                echo $user->username;

            }

        }

My editor is showing undefined variables where I'm declaring the arrays in the first block. I'm getting no output - Surely a syntax error and I'm struggling. Help would be appreciated !

Cheers, Mike

  • 1
    Start by enabling error reporting so you can post some useful error output. http://stackoverflow.com/questions/845021/how-to-get-useful-error-messages-in-php – alariva Jul 17 '15 at 02:46
  • Could be because you're overwriting your original `$hostnames` array with `$hostnames = $server_model->get_hostnames_for_costs();`... before you start your `foreach` loop – Darren Jul 17 '15 at 02:58

1 Answers1

0

In PHP there's no need to "build" an array and then populate it. You can create the array as you populate it.

In your first block, it is throwing errors because it doesn't know what $host, $hostname, $users, $key or $username is, i.e. they are undefined.

I'm not sure what structure you want your final array to be as I'm not sure what $key, $host, etc. is meant to be and there's a million ways to create an array depending on what you need, but here's an example of what you can do:

// Get all hostnames
$hostnames = $server_model->get_hostnames_for_costs();
// Iterate through each hostname
foreach ($hostnames as $hostname) 
{
    // Get all users of the hostname
    $usernames = $userlogons_model->get_users_by_hostname($hostname);
    // Iterate through each user and append it to the user array
    $user_arr = array();
    foreach($usernames as $user)
    {
        // Append the user to the user array
        $user_arr[] = $user;
    }
    // Add the user array to your 
    $my_arr[] = array (
        'host' => $hostname,
        'users' => $user_arr
    );
}

echo var_dump($my_arr);
mongjong
  • 479
  • 3
  • 6