Batıkan Genç ACAT Batıkan Genç ACAT - 11 months ago 129
JSON Question

Json Array in Array foreach

I wan't create word-ban system into technical support script.

But I can't imagine how to design json and foreach in them.


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

How JSON design should be and how can I foreach in them?

I'm checking ticket messages with strpos() function.

Answer Source

What you have there isn't valid JSON. (I assume you already knew that.) To turn what you have into valid JSON, you'll need to change a couple of things.

  • Quote all your keys and string values with ".

  • For your list of words in each object in banned_words, you'll need to enclose them in an array [] and assign them a key.

You should end up with JSON like this:

{"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"

After you have the JSON, you can loop over the lists of words and their corresponding messages like this:

$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

(How to actually implement the word ban system from this point is beyond the scope of a Stack Overflow answer.)