Search code examples
phparrayssortingarray-difference

PHP finding same record in array


I would like to detect same records and then change quantity of the one record and delete the others. For example, given the following array:

'Cart' => [
    (int) 0 => [
        'size' => '38',
        'code' => '5',
        'qn' => (int) 1
    ],
    (int) 1 => [
        'size' => '37',
        'code' => '5',
        'qn' => (int) 1
    ],
    (int) 2 => [
        'size' => '37',
        'code' => '5',
        'qn' => (int) 1
    ]
],

i would like to print:

'Cart' => [
    (int) 0 => [
        'size' => '38',
        'code' => '5',
        'qn' => (int) 1
    ],
    (int) 1 => [
        'size' => '37',
        'code' => '5',
        'qn' => (int) 2
    ]

],

Solution

  • It looks to me that you're trying to sum quantities (qn) on duplicate sizes (size) and codes (code). One way to achieve this is by looping through the array containing the cart items and building out a new array. I suggest reading about PHP arrays and array_key_exists to learn more as they're used below:

    <?php
    
    $arr = [
        ['size' => '38', 'code' => 5, 'qn' => 1],
        ['size' => '37', 'code' => 5, 'qn' => 1],
        ['size' => '37', 'code' => 5, 'qn' => 1],
        ['size' => '37', 'code' => 4, 'qn' => 1],
    ];
    
    $newArr = [];
    
    foreach ($arr as $value) {
        $key = $value['size'] . ':' . $value['code'];
    
        if (array_key_exists($key, $newArr)) {
            $newArr[$key]['qn'] += $value['qn'];
            continue;
        }
    
        $newArr[$key] = $value;
    }
    
    // Resets keys
    $newArr = array_values($newArr);
    
    print_r($newArr);