0

I have the following php array and would like to group the results:

array:3 [▼
  1 => array:4 [▼
    "trashed" => 1
    "passed" => 0
    "failed" => 2
    "unknown" => 0
  ]
  2 => array:4 [▼
    "trashed" => 0
    "passed" => 1
    "failed" => 0
    "unknown" => 3
  ]
  3 => array:4 [▼
    "trashed" => 0
    "passed" => 0
    "failed" => 0
    "unknown" => 0
  ]
]

How can i group them for example: without going through loops? I would love to learn about an array_sort or merge function that does this :D

$trashed = [1, 0, 0];
$passed = [0, 1, 0];

I can rename the $key to anything if numbers is better approach or may assist in answering the question.

There will not be any null $keys or $values in this.

I'm currently doing it like this, but it seems ugly:

$trashed = [];
    
foreach($months as $month){
    array_push($trashed, $month['trashed']);
}
2
  • 1
    What's wrong with loops? Commented Nov 15, 2020 at 8:52
  • @Cid nothing really, I'm just interested in learning a new approach if available/possible :) Commented Nov 15, 2020 at 8:53

1 Answer 1

2

You may want to use array_column() for this, as is demonstrated by the example below. Keep in mind though, that array_column() does internal looping of its own. It's good to see you're eager to learn new/other solutions, but generally performance and simplicity are some of the basic goals of any application.

If you want to avoid using a loop, then I suggest building the array differently in the first place. Why not use the trashed etc. keys as keys to their own respective arrays?

Here's one possible approach using array_column(). See comments for explanation and output.

<?php

// Your input array.
$a = [
    1 => [
            'trashed' => 1,
            'passed' => 0,
            'failed' => 2,
            'unknown' => 0
    ],
    2 => [
            'trashed' => 0,
            'passed' => 1,
            'failed' => 0,
            'unknown' => 3
    ],
    3 => [
            'trashed' => 0,
            'passed' => 0,
            'failed' => 0,
            'unknown' => 0
    ],
];

// Fetch all values for each key and return them as an array.
$trashed = array_column($a, 'trashed');
$passed = array_column($a, 'passed');
$failed = array_column($a, 'failed');
$unknown = array_column($a, 'unknown');

var_dump($trashed);
var_dump($passed);
var_dump($failed);
var_dump($unknown);
/*
Output:
array(3) {
  [0]=>
  int(1)
  [1]=>
  int(0)
  [2]=>
  int(0)
}
array(3) {
  [0]=>
  int(0)
  [1]=>
  int(1)
  [2]=>
  int(0)
}
array(3) {
  [0]=>
  int(2)
  [1]=>
  int(0)
  [2]=>
  int(0)
}
array(3) {
  [0]=>
  int(0)
  [1]=>
  int(3)
  [2]=>
  int(0)
}
*/
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.