-2

I have a Array list as below, how to split them into equal parts, sort equal parts by id, and merge equal parts in a id using PHP?

Array
(
    [0] => Array
        (
            [id] => 121
            [owner] => xa
            [name] => xjs
        )

    [1] => Array
        (
            [id] => 139
            [owner] => xa
            [name] => xjs
        )

    [2] => Array
        (
            [id] => 1456
            [owner] => xv
            [name] => bjs
        )
    [3] => Array
        (
            [id] => 1896
            [owner] => xb
            [name] => bjs
        )
    [4] => Array
        (
            [id] => 1963
            [owner] => xb
            [name] => bjs
        )

)

Supposed I would like to split them into 2 equal items, Split them firstly, and the smallest id should be in a equal part at first, they should be like this:

Array
(
    [0] => Array
        (
            [id] => 121
            [owner] => xa
            [name] => xjs
        )

    [1] => Array
        (
            [id] => 139
            [owner] => xa
            [name] => xjs
        )
)
Array
(
    [0] => Array
        (
            [id] => 1456
            [owner] => xv
            [name] => bjs
        )
    [1] => Array
        (
            [id] => 1896
            [owner] => xb
            [name] => bjs
        )
)


Array
(
    [0] => Array
        (
            [id] => 1963
            [owner] => xb
            [name] => bjs
        )
)

my sample code is 5 items, and if 6 items, it should be [1,2],[3,4],[5,6], how many items or parts are not sure, but i should be 2 equal pieces.

Merge them secondly(This is our logic of our project, if you don't know what I am talking about, please ignore the merge question, I only need to know how to split them):

[121, 139] => merge into 139, [1456, 1896] => merge into 1896, new list: [139, 1896] => merge into 1896, and the final list [1896, 1963] merge into the final id 1963

Elsa
  • 1
  • 1
  • 8
  • 27

1 Answers1

1

Sounds like you wanted something like this:

$array = [
    [
        'id' => 121,
        'owner' => 'xa',
        'name' => 'xjs',
    ],
    [
        'id' => 139,
        'owner' => 'xa',
        'name' => 'xjs',
    ],
    [
        'id' => 1456,
        'owner' => 'xv',
        'name' => 'bjs',
    ],
    [
        'id' => 1896,
        'owner' => 'xb',
        'name' => 'bjs',
    ],
    [
        'id' => 1963,
        'owner' => 'xb',
        'name' => 'bjs',
    ]
];

// custom function to compare which ID is greater
function customCompare($a, $b)
{
    if ($a['id'] === $b['id']) {
        return 0;
    }
    
    return ($a['id'] < $b['id']) ? -1 : 1;
}

// sort the whole array
usort($array, "customCompare");

// print the whole array as pairs,
// if there is an unpair number
// the last one will be a single member
print_r(array_chunk($array, 2));
lewis4u
  • 14,256
  • 18
  • 107
  • 148