How to ignore json elements and capture only those that are correct = true

Asked

Viewed 48 times

0

I need to take only the value of the objects that have correct:true and if you do not need to return []

"questions": [{
    "title": "Qual é a raça de Goku?",
    "image": {
        "path": ""
    },
    "alternatives": [{
        "title": "Sayajins",
        "image": {
            "path": ""
        },
        "correct": true
    }, {
        "title": "Anjo",
        "image": {
            "path": ""
        }
    }, {
        "title": "Android",
        "image": {
            "path": ""
        }
    }],
    "alternativeType": 1
}

It would have to stay that way

    "questions": [{
        "alternatives": [{
                "correct": true
            },
            [],
            []
        ]
    }
  • Have you tried anything? You could put the code in the question and what was the result obtained?

1 answer

1


Your json had some formatting errors that I fixed and put inside the code phpto illustrate better. Below is a way to clean the json going through the questions and their alternatives removing the parameters:

<?php

$questions = json_decode('{"questions": [{ "title": "Qual é a raça de Goku?", "image": { "path": "" }, "alternatives": [{ "title": "Sayajins", "image": { "path": "" }, "correct": true }, { "title": "Anjo", "image": { "path": "" } }, { "title": "Android", "image": { "path": "" } }], "alternativeType": 1 }] }');
$questions = $questions->questions;

for($i=0; $i<count($questions); $i++){
    unset($questions[$i]->title);
    unset($questions[$i]->image);
    unset($questions[$i]->alternativeType);
    for($j=0; $j<count($questions[$i]->alternatives); $j++){
        if(isset($questions[$i]->alternatives[$j]->correct) && !$questions[$i]->alternatives[$j]->correct) {
            $questions[$i]->alternatives[$j] = []; 
        } else {
            unset($questions[$i]->alternatives[$j]->title);
            unset($questions[$i]->alternatives[$j]->image);
        }
    }
}

echo json_encode($questions);

?>
  • 1

    Thank you! , exactly what I needed!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.