anvd
anvd

Reputation: 4047

Create multidimensional array for certain attributes

I have this array structure. The ID 145 is a request with two associated relations to another table - the project id 16 and 17. So, one request can have multiples projects.

Now I want to change this structure and merge the duplicated info. I mean, merge [0] and [n]. So funding_project_name and relation_id will become two entries for a new sub-array.

[145] => Array
(
    [0] => Array
        (
          [firstname] => John
          [institution] => Harvard
          [funding_project_name] => Project 1 #add to array funding_project_name - [0]
          [relation_id] => 16                 #add to array relation_id  - [0]
        )
    [1] => Array
        (
          [firstname] => John //discard
          [institution] => Harvard //discard
          [funding_project_name] => Project 2 #add to array funding_project_name - [1]
          [relation_id] => 17                 #add to array relation_id  - [1]
        ) 
)

I achieved this output using:

$query->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC)

Any idea how can I get the intended structure? Already tried some nested foreach, however not sure how to group the items

Expected:

[145] => Array
    (
      [firstname] => John
      [institution] => Harvard
      [projects] => Array(
          [0] => Array(
              [funding_project_name] => Project 1
              [relation_id] => 16           
          )
          [1] => Array(
               [funding_project_name] => Project 2
               [relation_id] => 17
          )
      )
    )

Upvotes: 2

Views: 42

Answers (1)

dWinder
dWinder

Reputation: 11642

If only the 2 fields are changing then you can loop on all keys and gather the data - later just find for uniqueness if needed and convert to string:

$array = array_map(function ($arr) {
    foreach(array_keys($arr[0]) as $k) {
        $vals = array_column($arr, $k);
        $e[$k] = count(array_unique($vals)) == 1 ? $vals[0] : $vals;
    }
    return $e;
}, $array);

Live example: 3v4l

If do you prefer - this is the older code version:

$array = array_map(function ($arr) {
    $a = array('first' => $arr[0]['first'], 'last' => $arr[0]['last']);
    foreach($arr as $e) {
        $a['funding_project_name'][] = $e['funding_project_name'];
        $a['relation_id'][] = $e['relation_id'];
    }
    return $a;}, $array);

Reference: array-keys, array_unique, array-column, array_map

Upvotes: 1

Related Questions