猿问

分解数组结果并申请 foreach

这是我的数组,


array:2 [

  0 => "{"1":[2],"2":[1,3]}"

  1 => true

]

如何以相应的格式显示上述数组


item_id | item_value_id

   1             2

   2             1

   2             3

我尝试使用 explode,但不幸的是我无法解析括号中的黑白。


这是我尝试过的


        // dd(explode("[]", $value));

        // dd(preg_split('/"/', $value));

        // dd(preg_split('/(?![^][]*\])/', $value));

我没有得到预期的结果。


更新:


我把数组缠绕在json_decode上,我得到了


        foreach ($arrays as $key => $value) {

                    # code... 

                    $json = json_decode($value);

   

//Another foreach 

                    foreach ($json as $key => $value1) {

                        # code...

                        dd($value1);

    

                    }

                }

结果


**dd($json)**

 /**

            {#1386

              +"1": array:1 [

                0 => 2

              ]

              +"2": array:2 [

                0 => 1

                1 => 3

              ]

            }

        */


**dd($value)**


   /**

    array:1 [

      0 => 2

    ]

    **/


炎炎设计
浏览 133回答 2
2回答

小唯快跑啊

我不确定我在这里是否完全正确,但我相信这就是你所要求的:<?php$data = [&nbsp; &nbsp; 0 => '{"1":[2],"2":[1,3]}',&nbsp; &nbsp; 1 => true];$decoded_json = json_decode($data[0], true);?><table>&nbsp; &nbsp; <thead>&nbsp; &nbsp; &nbsp; &nbsp; <th>item_id</th>&nbsp; &nbsp; &nbsp; &nbsp; <th>item_value_id</th>&nbsp; &nbsp; </thead>&nbsp; &nbsp; <tbody>&nbsp; &nbsp;<?php foreach ($decoded_json as $item_key => $item){?>&nbsp; &nbsp; &nbsp; &nbsp; <?php foreach ($item as $item_data){ ?>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <td><?php echo $item_key?></td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <td><?php echo $item_data?></td>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </tr>&nbsp; &nbsp; &nbsp; &nbsp; <?php }?>&nbsp; &nbsp; <?php } ?>&nbsp; &nbsp; </tbody></table>

温温酱

&nbsp; &nbsp; 除非对象实现 Countable 或 ArrayAccess 接口,否则无法循环对象。 假设您的模型名称是 ,您可以执行如下批量插入:Model<?php$rows = [];$arrays = json_decode($data[0],true);foreach ($arrays as $key1 => $value) {&nbsp; &nbsp; foreach ($value as $key2 => $value2) {&nbsp; &nbsp; &nbsp; &nbsp; $rows[] = [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'item_id' => $key1,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'item_value_id' => $value2&nbsp; &nbsp; &nbsp; &nbsp; ];&nbsp; &nbsp; }}if(count($rows) > 0){&nbsp; &nbsp; Model::insert($rows); // bulk insert}
随时随地看视频慕课网APP
我要回答