为了账号安全,请及时绑定邮箱和手机立即绑定

Laravel:获取数据数组并使用 For 循环

Laravel:获取数据数组并使用 For 循环

PHP
温温酱 2021-08-28 09:01:06
我正在尝试获取数据数组并使用 For 循环。所以我有一个名为“颜色”的数组,我想用 For 循环数组。但我在结果上遇到了一些麻烦。我已经尝试在 foreach 中更改数组,但我不知道如何获得我想要的结果。结果 :"data": [        {            "title": "get data users",            "function_name": "selectDataUser",            "function_drop": "selectDataUser",            "type_of_chart": "Pie",            "embed": null,            "created_at": "2019-06-15 03:26:09.000",            "updated_at": null,            "data_chart": [                {                    "name": "Administrator",                    "total": "100",                    "color": "0xFF888888" //color cannot be the same                },                {                    "name": "Staff",                    "total": "100",                    "color": "0xFF888888" //the color must be different                },                {                    "name": "Super Administrator",                    "total": "1",                    "color": "0xFF888888" //this is not result what I want.                }            ],      }  ]我想要这样的回应: "data": [            {                "title": "get data users",                "function_name": "selectDataUser",                "function_drop": "selectDataUser",                "type_of_chart": "Pie",                "embed": null,                "created_at": "2019-06-15 03:26:09.000",                "updated_at": null,                "data_chart": [                    {                        "name": "Administrator",                        "total": "100",                        "color": "0xFF000000" //all this color different                    },                    {                        "name": "Staff",                        "total": "100",                        "color": "0xFF444444" //the color different                    },                    {                        "name": "Super Administrator",                        "total": "1",                        "color": "0xFF888888" //this is result what I want.                    }                ],}  ]
查看完整描述

1 回答

?
MM们

TA贡献1886条经验 获得超2个赞

$set是数组,不能作为字符串赋值。我的建议是更改以下代码:


        for ($i=0; $i < count($data_chart) ; $i++) { 

            $set = $color[$i]; //Get data array color

        }



        foreach($data_chart as $row){

            $row->color = $set;

        }


        $i=0; 

        foreach($data_chart as $row){

            $row->color = $color[$i];

            $i++;

        }

但是如果您的$data_chart计数超过$color计数,它将返回错误,以便更好地处理使用以下代码:


        $i=0; 

        foreach($data_chart as $row){

            if(isset($color[$i])){

            $row->color = $color[$i];

            $i++; }

            else{

            $i=0;

            }


        }


查看完整回答
反对 回复 2021-08-28
  • 1 回答
  • 0 关注
  • 257 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信