0

I have an array of arrays called user_ids:

$user_ids = Array( 
  [0] => Array ( [0] => 12 ) 
  [1] => Array ( [0] => 13 ) 
  [2] => Array ( [0] => 14 ) 
)

I have a function called flatten_ar that returns an array that breaks it one level:

    function flatten_ar($ar,$flat_ar) {

      for($i=0; $i <= count($ar); $i++) {
        if(is_array($ar[$i])) {
          $flat_ar = flatten_ar($ar[$i], $flat_ar);
        } else {
          if(isset($ar[$i])) {
            $flat_ar[] = $ar[$i];
          };
        };
      };

      return $flat_ar;

    };

I create a new array called $user_ids_ar that calls the function, converts the entries to strings, and prints the results:

$user_ids_ar = flatten_ar($user_ids, array());
            $user_ids_ar = json_decode(json_encode($user_ids));
            print_r($user_ids_ar);



$user_ids_ar = json_decode(json_encode($user_ids));
            print_r($user_ids_ar);

However, I get multiple errors for each entry:

Notice: Undefined offset: 1 in C:\..\index.php on line 30
Call Stack
#   Time    Memory  Function    Location
1   0.0019  244528  {main}( )   ...\index.php:0
2   0.0066  271544  flatten_ar( )   ...\index.php:24
3   0.0067  271592  flatten_ar( )   ...\index.php:31

Followed by the output of the new array, which has done the opposite of what I wanted.

Array ( 
[0] => Array ( 
  [0] => 12 ) 
  [1] => Array ( 
    [0] => 13 ) 
    [2] => Array ( 
     [0] => 14 
    )
  )
)

The array I expected:

Array(
  [0] => "12"
  [1] => "13"
  [2] => "14"
)

How do I get the expected array?

2 Answers2

1

For example:

$a = array();
foreach($user_ids as $row)
  $a[] = (string)$row[0];
print_r($a);

http://php.net/manual/en/language.types.array.php

kurkle
  • 353
  • 1
  • 2
  • 6
1

You can use the built-in array_walk_recursive to iterate all the ids in $user_ids regardless of depth, and append their string values to your result array in the callback.

$user_ids_ar = [];

array_walk_recursive($user_ids, function($id) use (&$user_ids_ar) {
    $user_ids_ar[] = strval($id);
});

If your input array is only one level deep like the example in your question, then you don't need recursion, you can just map strval over column 0.

$user_ids_ar = array_map('strval', array_column($user_ids, 0));
Don't Panic
  • 41,125
  • 10
  • 61
  • 80