codeigniter 使用条件[closed]操作对象的php数组

5cg8jx4n  于 2022-12-07  发布在  PHP
关注(0)|答案(2)|浏览(116)

**已关闭。**此问题需要debugging details。当前不接受答案。

编辑问题以包含desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将有助于其他人回答问题。
8个月前关闭。
Improve this question
这可能很简单,但我真的很难做到这一点,我有一个输出数据与数组的对象像这样:

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对象和跳过其他人,有人能帮助我如何做到这一点吗?谢谢你,我真的很感激

um6iljoc

um6iljoc1#

您可以通过创建一个临时数组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
    )

)
0yg35tkg

0yg35tkg2#

那你可以试试下面的样子:

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

当发现anggota和jenis时,它将中断流。

相关问题