简体   繁体   中英

How to Group array then iterate

I have trouble with my project.

First, I have a data like this : https://jsoneditoronline.org/?id=c6d15407962e4d1b986435ad3c283b4e

Then I group the data using this:

private function _group_by($array, $key) {
    $new = [];
    foreach ($array as $value) {
        $new[$value[$key]][] = $value;
    }

    return $new;
}

$key = 'water_id'

After that the following result is like this: https://jsoneditoronline.org/?id=72991d45938c49a38900703feb3a60e7

From result above I cant iterate the data (I want to iterate since beginning). So, I want to able iterate the data, it is something wrong with my group by array function ? If you understand what I want, please help.

You can use collections to manipulate arrays or Traversable objects. Grouping in CakePHP's Collection

use Cake\Collection\Collection;

private function _group_by($array, $key) {
    $collection = new Collection($array);
    return $collection->groupBy('water_id')->toArray();
}

You tagged this as being a Laravel App, right? Check out Collections: https://laravel.com/docs/5.6/collections .

$result = null;
collect($array)->groupBy($keyName)->each(function ($group, $key) use (&$result) {
    foreach ($group as $element => $index) {
        //Do something to $result.
    }
});

Depending on your circumstances, map or transform might be more appropriate than each .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM