Search code examples
phparrayscodeigniter

Manipulate php array of object with condition


It's maybe simple but i was really struggling with this, i have an ouput data with array of object like this :

Array
(
    [0] => stdClass Object
        (
            [jumlah] => 50000
            [jenis] => 41
            [anggota] => 1
            [dk] => D
        )

    [1] => stdClass Object
        (
            [jumlah] => 100000000
            [jenis] => 40
            [anggota] => 1
            [dk] => D
        )

    [2] => stdClass Object
        (
            [jumlah] => 1000000
            [jenis] => 32
            [anggota] => 2
            [dk] => D
        )

    [3] => stdClass Object
        (
            [jumlah] => 4000000
            [jenis] => 40
            [anggota] => 1
            [dk] => D
        )

)

i want to minus all jumlah values but if there same jenis and anggota data value in different object it will manipulate just 1 object and skip the others, can anyone help me how to do this? thank you and i really appreciate


Solution

  • You can do this by creating a temporary array lookup, that has elements with key of jenis,angotta. We look through the data array, and modify the object if the key does not exist in the lookup array.

    <?php
    
    $array = [
        (object) [
            'jumlah' => 50000,
            'jenis' => 41,
            'anggota' => 1,
            'dk' => 'D'
        ],
        (object) [
            'jumlah' => 100000000,
            'jenis' => 40,
            'anggota' => 1,
            'dk' => 'D'
        ],
        (object) [
            'jumlah' => 1000000,
            'jenis' => 32,
            'anggota' => 2,
            'dk' => 'D'
        ],
        (object) [
            'jumlah' => 4000000,
            'jenis' => 40,
            'anggota' => 1,
            'dk' => 'D'
        ]
    ];
    
    $lookup = [];
    
    foreach ($array as &$object) {
        $key = $object->jenis . ',' . $object->anggota;
        if (!isset($lookup[$key])) {
            $object->jumlah -= 2500;
            $lookup[$key] = true;
        }
    }
    
    print_r($lookup);
    print_r($array);
    

    Results in:

    Array
    (
        [41,1] => 1
        [40,1] => 1
        [32,2] => 1
    )
    
    Array
    (
    [0] => stdClass Object
        (
            [jumlah] => 47500
            [jenis] => 41
            [anggota] => 1
            [dk] => D
        )
    
    [1] => stdClass Object
        (
            [jumlah] => 99997500
            [jenis] => 40
            [anggota] => 1
            [dk] => D
        )
    
    [2] => stdClass Object
        (
            [jumlah] => 997500
            [jenis] => 32
            [anggota] => 2
            [dk] => D
        )
    
    [3] => stdClass Object
        (
            [jumlah] => 4000000
            [jenis] => 40
            [anggota] => 1
            [dk] => D
        )
    
    )