使用条件操作 php 对象数组

Manipulate php array of object with condition

这可能很简单,但我真的为此苦苦挣扎, 我有一个像这样的对象数组的输出数据:

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
        )

)

我想减去所有 jumlah 值,但如果不同对象中有相同的 jenis 和 anggota 数据值,它将只处理 1 个对象并跳过其他对象, 谁能帮我怎么做?谢谢你,我真的很感激

您可以通过创建一个临时数组 lookup 来完成此操作,该数组包含键为 jenis,angotta 的元素。我们查看数据数组,如果查找数组中不存在该键,则修改对象。

<?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);

结果:

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
    )

)

那你可以试试下面的方法:

foreach($array as $key => $value) {
    $value->jumlah = $value->jumlah - 2500;
    if(isset($value->anggota) && isset($value->jenis)) {
        break;
    }
}

当找到 anggota 和 jenis 时,它会中断流程。