php 返回重复值的数组

php array returning duplicate values

我正在尝试遍历每个键,但我遇到了一个问题,即每个循环在内部重复相同的值

Please be noted we should keep on same code structure multiple foreach it's requirement i already posted this question here but didn't get solution instead of solution entire new code as answer imposed on me and nobody is actually taking care of it

Here is example of my current code and result (click here)

到目前为止,这是我的代码

<?php
    $data2 = array(
        'category_name' => '33287*100*prescription*1,32457*1250*lab*1'
    );
    $result = array('0' => (object)$data2);

    foreach ($result as $key => $category) {
        $category_name = explode(',', $category->category_name);
    }

    $newresults=[];
    foreach ($category_name as $key) {
        $category->category_name = $key;
        $newresults[]=$category;
    }    
    $result=$newresults;

    $newresults=[];
    $category->items_count = 0;
    foreach ($result as $key => $value) {
        list($sale_key, $sale_value) = explode('*', $value->category_name);
        // $category->items_count += count($sale_value);
        $newresults[]=$category;
    }
    $result=$newresults;

   

我得到这样的错误结果

Array
(
    [0] => stdClass Object
        (
            [category_name] => 33287*100*prescription*1
        )

    [1] => stdClass Object
        (
            [category_name] => 33287*100*prescription*1
        )

)

如前所述,因为您正在重用变量名,并且还在它们的范围可能不正确或不被接受时使用它们,所以您造成了一些混乱。

下面的代码将底部循环 置于顶部循环的 内部,因为这是上下文真正存在的地方。创建一个临时循环只会增加潜在的混乱。如果这不适用于附加逻辑,则需要进行更多更改。我还更改了一堆变量名,希望能让事情变得更明显。详情请见代码中的注释。

$reporting_data = array(
    'category_name' => '33287*100*prescription*1,32457*1250*lab*1,32459*1500*lab*1,32460*400*lab*1,32461*600*lab*1,32468*950*lab*1,32470*950*lab*1,33291*2500*lab*1,33292*2500*lab*1,47516*2000*lab*1,49209*0*lab*1,56835*2400*lab*1,56836*2400*lab*1',
    'patient' => '28370',
    'date' => 1643030497,
    'ref' => '371',
);

// Create array of objects
$reporting_data_as_objects[] = (object)$reporting_data;

$results = [];
foreach ($reporting_data_as_objects as &$obj) {

    // Setup base data that is shared across all items
    $obj->reception_data_sum = 0;
    $obj->references_data_sum = 0;
    $obj->actual_price = 0;

    $category_names = explode(',', $obj->category_name);

    // Loop over the comma-delimited parts of category_name
    foreach ($category_names as $category_name) {

        // Clone our template object
        $tmp = clone $obj;

        // The second item of the asterisk-delimted field is the price
        // We used $_ to indicate that we aren't interested in the first item.
        list($_, $sale_value) = explode('*', $category_name);

        // Set object-specific fields on our clone
        $tmp->category_name = $category_name;
        $tmp->actual_price = (int)$sale_value;

        // Add the clone to the array
        $results[] = $tmp;
    }
}

// Always unset by-ref variables of a foreach
unset($obj);

print_r($results);

此处演示:https://3v4l.org/95KAQ