Home > Back-end >  Structure array into multi dimensional array
Structure array into multi dimensional array

Time:02-24

So I have the following variable $authenticated_users which returns:

array(2) {
  [0]=>
  array(5) {
    ["username"]=> string(16) "saint"
    ["user_id"]=> int(17841404774727369)
    ["access_token"]=> string(142) "IGQ3"
    ["access_token_expiration"]=> int(1650688769)
    ["last_updated"]=> int(1645537675)
  }
  [1]=>
  array(5) {
    ["username"]=> string(9) "sem"
    ["user_id"]=> int(17841400835712753)
    ["access_token"]=> string(140) "IGQ"
    ["access_token_expiration"]=> int(1650683675)
    ["last_updated"]=> int(1645537891)
  }
}

So I have the following method:

public static function get_config_and_users(): array
{
    $config = [];
    $config['client_id'] = '2882';
    $config['client_secret'] = '521f4e';

    if (!$authenticated_users = get_option('instagram')) {
        return [];
    }

    foreach ($authenticated_users as $user) {
        $config['authenticated_users'] = [
            $config['username'] = $user['username']
        ];
    }

    echo '<pre>';
    var_dump($config);
    echo '</pre>';
    die();

    return $config;
}

When I echo $config I get the following results:

array(4) {
  ["client_id"]=> string(15) "28822"
  ["client_secret"]=> string(32) "521f4e8"
  ["username"]=> string(9) "sem"
  ["authenticated_users"]=> array(1) {
    [0]=> string(9) "sem"
  }
}

Here is what I'm attempting to do:

array(4) {
    ["client_id"]=> string(15) "2882"
    ["client_secret"]=> string(32) "521f4e5"
    ["authenticated_users"] => {
      [0]=> array(1) { 
            ['username']=> string(16) "saint"
            ....
      }
      [1]=>
      array(1) {
            ['username']=> string(9) "sem"
            ....
      }
    }
}

Does anyone know what I can do to improve my code?

CodePudding user response:

you need to change your logic

public static function get_config_and_users(): array
{
    $config = [];
    $config['client_id'] = '2882';
    $config['client_secret'] = '521f4e';

    if (!$authenticated_users = get_option('instagram')) {
        return [];
    }

    foreach ($authenticated_users as $user) {
        $config['authenticated_users'][] = [
            'username' => $user['username']
        ];
    }

    return $config;
}
  •  Tags:  
  • php
  • Related