这个php 数组咋处理,请教下

$mouth = [3,4,5,6,7,8,9,10,11,12];
$list ='[
    {
        "id": 1,
        "year": 2021,
        "org_id": 1,
        "text": "{\"1\":0,\"2\":0,\"3\":0,\"4\":0,\"5\":0,\"6\":0,\"7\":0,\"8\":0,\"9\":0,\"10\":0,\"11\":0,\"12\":0}",
        "mid": 6,
        "dues": "100.00"
    },
    {
        "id": 2,
        "year": 2021,
        "org_id": 1,
        "text": "{\"1\":0,\"2\":0,\"3\":0,\"4\":0,\"5\":0,\"6\":0,\"7\":0,\"8\":0,\"9\":0,\"10\":0,\"11\":0,\"12\":0}",
        "mid": 7,
        "dues": "500.00"
    }
]';

如何处理使text字段,把text字段json转成数组,使$mouth中存在的值等于text字段中的键时把值赋值成 dues字段

阅读 1.5k
2 个回答

能举一个列子吗

首先month单词写错了,写成了mouth,单词记不住的话可以百度翻译一下。

然后呢,你这个$list应该是一堆json数据,我把你问题编辑了一下,改了一下,不知道你写程序多久了,反正我是觉得非常非常不可思议。

其他我不多说,直接上代码吧,这种东西毫无难度啊。

<?php
$month = [3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
$list  = '[
    {
        "id": 1,
        "year": 2021,
        "org_id": 1,
        "text": "{\"1\":0,\"2\":0,\"3\":0,\"4\":0,\"5\":0,\"6\":0,\"7\":0,\"8\":0,\"9\":0,\"10\":0,\"11\":0,\"12\":0}",
        "mid": 6,
        "dues": "100.00"
    },
    {
        "id": 2,
        "year": 2021,
        "org_id": 1,
        "text": "{\"1\":0,\"2\":0,\"3\":0,\"4\":0,\"5\":0,\"6\":0,\"7\":0,\"8\":0,\"9\":0,\"10\":0,\"11\":0,\"12\":0}",
        "mid": 7,
        "dues": "500.00"
    }
]';
$list  = json_decode($list, true);
foreach ($list as &$item) {
    $text = json_decode($item['text'], true);
    // 第一种方式处理text数据
    foreach ($month as $monthItem) {
        $text[$monthItem] = $item['dues'];
    }
    // 第二种方式处理text数据
    /*foreach ($text as $textKey => &$textItem) {
        if (in_array($textKey, $month)) {
            $textItem = $item['dues'];
        }
    }*/
    $item['text'] = $text;
}
var_dump($list);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题