1

I have an array that looks like this:

[
    [
        'name' => 'Umber',
        'reason' => 'No data',
        'id' => '12'
    ],
    [
        'name' => 'Jakar',
        'reason' => 'Wrong format',
        'id' => '12'
    ],
    [
        'name' => 'Lane',
        'reason' => 'No data',
        'id' => '12'
    ],
    [
        'name' => 'Jake',
        'reason' => 'Not found',
        'id' => '13'
    ],
    [
        'name' => 'Jame',
        'reason' => 'Wrong name',
        'id' => '13'
    ],
    [
        'name' => 'Joe',
        'reason' => 'No data',
        'id' => '13'
    ]
];

What I want to do is group these elements in a table row if the same id value:

12 | No data, wrong format, No data
13 | Not found, Wrong name, No data

I know I have to use foreach for this one but the logic for grouping these elements in a single row is beyond me. Any help would be appreciated. Thanks in advance. I've started with this.

foreach($a as $value){
    echo $value['id'] . ' ' . $value['reason'];
}
1

3 Answers 3

6

First group elements to subarrays, then output each subarray:

$groups = [];
foreach($a as $value){
    $groups[$value['id']][] = $value['reason'];
}

foreach ($groups as $key => $value) {
    echo $key . ' | ' . implode(', ', $value);
}
Sign up to request clarification or add additional context in comments.

Comments

1

Something like this, perhaps. It should help get you started:

$output = [];
foreach ($arrary as $arr) {
    $output[$arr['id']][] = $arr['reason'];
}

foreach ($output as $k => $v) {
    echo $k;
    echo implode(',', $v);
}

Comments

0

In PHP, it is not necessary to declare an empty parent array before pushing data into it using square brace syntax.

Use the id values as keys and push the reason values into the group's array.

Codes: (Demo)

$result = [];
foreach ($array as $row) {
    $result[$row['id']][] = $row['reason'];
}
var_export($result);

Or functional syntax:

var_export(
    array_reduce(
        $array,
        function($result, $row) {
            $result[$row['id']][] = $row['reason'];
            return $result;
        },
        []
    )
);

Output:

array (
  12 => 
  array (
    0 => 'No data',
    1 => 'Wrong format',
    2 => 'No data',
  ),
  13 => 
  array (
    0 => 'Not found',
    1 => 'Wrong name',
    2 => 'No data',
  ),
)

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.