【问题标题】:Json Array in Array foreach数组foreach中的Json数组
【发布时间】:2016-10-03 18:28:01
【问题描述】:

我不想在技术支持脚本中创建禁词系统。

但我无法想象如何在其中设计json和foreach。

计划:

  "banned_words": [
    {
        word, word2, word3, word4
        message: why we banned this words
    }
    {
        help, mail, register, email
        message: we know whats the problem, be patient
    }
  ]

JSON 设计应该如何以及如何在其中进行 foreach?

我正在使用 strpos() 函数检查票务消息。

【问题讨论】:

    标签: php arrays json foreach


    【解决方案1】:

    您所拥有的不是有效的 JSON。 (我假设您已经知道这一点。)要将您拥有的内容转换为有效的 JSON,您需要更改一些内容。

    • 使用" 引用所有键和字符串值。

    • 对于banned_words 中每个对象中的单词列表,您需要 将它们包含在一个数组 [] 中并为其分配一个键。

    你应该得到这样的 JSON:

    {"banned_words": [
        {
            "words": ["word", "word2", "word3", "word4"],
            "message": "why we banned this words"
        },
        {
            "words": ["help", "mail", "register", "email"],
            "message": "we know whats the problem, be patient"
        }
      ]
    }
    

    获得 JSON 后,您可以循环遍历单词列表及其对应的消息,如下所示:

    $word_lists = json_decode($json);
    
    foreach ($word_lists->banned_words as $set) {
        $message = $set->message;
        foreach ($set->words as $word) {
            // do something with the word
        }
    }
    

    (如何从这一点实际实施单词禁令系统超出了堆栈溢出答案的范围。)

    【讨论】:

    • 我在 5 分钟前完成了,同样的 json,感谢您的回答。没错!
    猜你喜欢
    • 2019-12-08
    • 1970-01-01
    • 2023-03-11
    • 2011-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-25
    • 1970-01-01
    相关资源
    最近更新 更多