php - Creating and accessing arrays dynamically -


i'm trying create array dynamically strings. here code i'm trying use:

$users = get_users( $args_users ); $user_display = array();  $user_display_sorted = array(); foreach($users $user){     echo $user->id;     $first_name = get_user_meta($user->id, 'first_name', true);     $last_name = get_user_meta($user->id, 'last_name', true);     $name = $first_name.' '.$last_name;     array_push($user_display, $user->id);     array_push($user_display, $name);     $user_display_sorted = asort($user_display); } print_r($user_display); 

when print array following:
array ( [0] => 5 [1] => test person[2] => 6 [3] => adam person )

i output this:
array ( [0] [id] => 5 [name] => test person; [1] [id] => 6 [name] => adam person)

so i'd foreach loop on user_display_sorted array , access variables this:

foreach($user_display_sorted $user_display_sort){     echo $user_display_sort->id; } 

how can this?

you need push array of data want append instead of values separately:

foreach($users $user){     echo $user->id;     $first_name = get_user_meta($user->id, 'first_name', true);     $last_name = get_user_meta($user->id, 'last_name', true);     $name = $first_name.' '.$last_name;     array_push($user_display, array('id' => $user->id, 'name' => $name));     $user_display_sorted = asort($user_display); } 

following on comment asking how sort - since multidimensional array, sort using array_multisort() like this:

array_multisort($example, sort_asc, sort_natural, array_map(     function($row) {         return $row['name'];     },     $example )); 

however, dagon has suggested in multiple places, if objective sort value using id array key easier overall, i.e. start end:

foreach ($users $user) {     // ...     $user_display[$user->id] = $name; }  // sort, maintaining keys asort($user_display);  // output again if want foreach ($user_display $id => $name) {     echo 'user id ' . $id . ' has name ' . $name, php_eol; } 

demo here.

for sorting references, the php manual has great table explaining function suit.


Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -