2

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
          )
      )
    )
3
  • Can you share example for expected output? Commented Sep 3, 2019 at 14:27
  • @dWinder question updated Commented Sep 3, 2019 at 14:35
  • Updated my answer to more generic one - it will change all field if needed but still keep the order of the non-unique fields Commented Sep 3, 2019 at 15:02

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.