Skip to content

Instantly share code, notes, and snippets.

@M4R14
Last active October 2, 2017 02:16
Show Gist options
  • Select an option

  • Save M4R14/e76a8c7731f5bccf3d1d92dca37c203b to your computer and use it in GitHub Desktop.

Select an option

Save M4R14/e76a8c7731f5bccf3d1d92dca37c203b to your computer and use it in GitHub Desktop.
จัดกลุ่มข้อมูล
<?php
$data = [
(object) [
"id" => 1,
"number" => 0,
"text" => "000000000"
],
(object) [
"id" => 1,
"number" => 1,
"text" => "1111111111"
],
(object) [
"id" => 2,
"number" => 1,
"text" => "11111111100000000"
],
(object) [
"id" => 2,
"number" => 1,
"text" => "2222222222"
],
(object) [
"id" => 1,
"number" => 0,
"text" => "000001111111111"
],
(object) [
"id" => 2,
"number" => 0,
"text" => "xxxxxxxxxxx"
],
];
$nextDate = group((object)[
"data" => $data,
"condition" => function ($next, $data){
return (
$next->number == $data->number &&
$next->id == $data->id
);
},
"first" => function ($data){
return [
"id" => $data->id,
"number" => $data->number,
"text" => [$data->text]
];
},
"matching" => function ($next, $data){
$next->text[] = $data->text;
}
]);
print_r($nextDate);
<?php
function group( $input ){
$DEBUG = [];
$data = $input->data;
$first = $input->first;
$matching = $input->matching;
$condition = $input->condition;
$nextData = [];
foreach ($data as $key => $item) {
if(count($nextData)){
$found = (object) [
"point" => 0,
"key" => null
];
foreach ($nextData as $keyItem => $nextItem) {
if($condition($item, $nextItem)){
$found->point += 1;
$found->key = $keyItem;
break;
}
}
if( $found->point == 0){
$nextData[] = (object) $first($item);
}else {
$matching($nextItem, $item);
}
}else{
// 0
$nextData[] = (object) $first($item);
}
}
return $nextData;
};
Array
(
    [0] => stdClass Object
        (
            [id] => 1
            [number] => 0
            [text] => Array
                (
                    [0] => 000000000
                    [1] => 000001111111111
                )

        )

    [1] => stdClass Object
        (
            [id] => 1
            [number] => 1
            [text] => Array
                (
                    [0] => 1111111111
                )

        )

    [2] => stdClass Object
        (
            [id] => 2
            [number] => 1
            [text] => Array
                (
                    [0] => 11111111100000000
                    [1] => 2222222222
                )

        )

    [3] => stdClass Object
        (
            [id] => 2
            [number] => 0
            [text] => Array
                (
                    [0] => xxxxxxxxxxx
                )

        )

)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment