K
K
Kozlov2022-01-24 21:22:46
PHP
Kozlov, 2022-01-24 21:22:46

How to concatenate and fold JSON PHP?

There is a base in which strings with json are stored. It is required to collect all the lines in an array and count the values. array_merge writes that json_decode (with true flag) is not an array.

1.{"q1":"a1","q2":"a4","q3":"a4","q4":"a1","q5":"a2","q6":"a2","q7":"a2","q9":"a3","q10":"a2","q11":"a2","q12":"a2","q13":"a2","q14":"a3","q15":""}
2.{"q8":"a3","q10":"a1","q11":"a1","q12":"a1","q13":"a1","q15":""}

There are 80 such lines.

The output is required:
q1a1: 5, q1a2: 0, q1a3: 3 and so on.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Kozlov, 2022-01-24
@romandkoz

I decided. The question is closed.

Full code

if($result->num_rows > 0){
    $data = array();
    while ($row = $result->fetch_assoc()){
        $data[] = json_decode($row['data'], true);
    }
}
$i = 0;
    foreach ($data as $key => $value) {
       if ($data[$key]['q1'] == 'a1') {
        $i++;
       }
    }
echo $i;


For ease of use, several times in different places, I threw everything into a function
Code
$data = array();
if($result->num_rows > 0){
    while ($row = $result->fetch_assoc()){
        $data[] = json_decode($row['data'], true);
    }
}
function jsonCount($question, $answer){
    global $data;
    $i = 0;
    foreach ($data as $key => $value) {
       if ($data[$key][$question] == $answer) {
        $i++;
       }
    }
return $i;
}
echo jsonCount('q1', 'a1');
echo '<br>';
echo jsonCount('q1', 'a2');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question