-2

I've got a multidimensional array of the format:

Array
(
[0] => Array
    (
        [course_prefix] => AERO
        [0] => AERO
        [course_number] => 101
        [1] => 101
    )

[1] => Array
    (
        [course_prefix] => AERO
        [0] => AERO
        [course_number] => 102
        [1] => 102
    )

[2] => Array
    (
        [course_prefix] => AERO
        [0] => AERO
        [course_number] => 201
        [1] => 201
    )
)

And I'm attempting to perform three operations:

  1. unset all elements with the [0] and [1] keys,
  2. Combine the [course_prefix] and [course_number] values in each subarray,
  3. Flatten to a single array

So that the end result is

Array
(

"AERO 101",

"AERO 102",

"AERO 201"

)

I understand that array_map can combine two different arrays, and that unset removes elements, but how can I perform the operations when everything is in the same multidimensional array - e.g. unsetting elements not at top level, and combining values?

Marcatectura
  • 1,721
  • 5
  • 30
  • 49
  • 2
    Start by modifying your database fetch to return only an associative array, not both – Mark Baker Jan 18 '17 at 22:28
  • 3
    Why don't you just not create the `0`, `1` keys in the first place? It looks like this is coming from a database query. If you use `fetch_assoc` instead of `fetch_array`, it will just return the named indexes. – Barmar Jan 18 '17 at 22:29
  • 3
    You can also use the db query to combine the two columns for you as well, so you won't need to do it in PHP – Mark Baker Jan 18 '17 at 22:29
  • Possible duplicate of [How to "flatten" a multi-dimensional array to simple one in PHP?](http://stackoverflow.com/questions/526556/how-to-flatten-a-multi-dimensional-array-to-simple-one-in-php) – yivi Jan 18 '17 at 22:30
  • Thanks for the feedback; I'm actually very new to SQL and did not realize it was possible to concatenate columns inside a query (I also didn't realize PDO returns two versions of a DB's data in its response), so between revising my query and only fetching the associative array I've accomplished everything without processing the result in PHP – Marcatectura Jan 19 '17 at 01:14

1 Answers1

1

It's a simple array_map:

$new_array = array_map(function($row) {
    return $row['course_prefix'] . ' ' . $row['course_number'];
}, $array);
Barmar
  • 741,623
  • 53
  • 500
  • 612