简体   繁体   English

php 数组在循环中返回相同的值

[英]php array returning same values in loop

I am trying to loop through each key but i am facing a problem of same value repeating inside for each loop我正在尝试遍历每个键,但我面临每个循环内部重复相同值的问题

Here is example of my current code and result ( click here )这是我当前代码和结果的示例(单击此处

here is my code so far到目前为止,这是我的代码

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

   

i am expect the result should be我希望结果应该是

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

    [1] => stdClass Object
        (
            [category_name] => 32457*1250*lab*1
            [items_count] => 0
        )

)

The bug is that you're relying only on the last version of $category after you've finished looping it earlier - you'd have to be using it within the loop where it's assigned, in order to get each value in turn, or you could use $value from your last foreach loop.错误是您在较早完成循环后仅依赖$category的最后一个版本 - 您必须在分配它的循环中使用它,以便依次获取每个值,或者您可以使用上一个 foreach 循环中的$value

But as a general observation, this code has way too many loops etc. just for processing one array in the way you've requested.但作为一般观察,这段代码有太多的循环等,只是为了以您请求的方式处理一个数组。 Here's a much simpler version:这是一个更简单的版本:

$category_name = '33287*100*prescription*1,32457*1250*lab*1';
$category_name_arr = explode(',', $category_name);

print_r($category_name_arr);

$newresults=[];

foreach ($category_name_arr as $cat) {
    $newresults[] = (object) array("category_name" => $cat, "items_count" => 0);
}

print_r($newresults);

Demo: http://sandbox.onlinephpfunctions.com/code/065a32b40f67e00aa85f0f5b58ecacd510f2f38a演示: http://sandbox.onlinephpfunctions.com/code/065a32b40f67e00aa85f0f5b58ecacd510f2f38a

adding $category = new stdClass();添加 $category = new stdClass();

foreach ($category_name as $key) {
            

$category = new stdClass(); $category = 新的 stdClass();

            $category->category_name = $key;
            $newresults[]=$category;
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM