Combine 2 arrays by matching the same foreign key

后端 未结 2 1885
死守一世寂寞
死守一世寂寞 2021-01-28 23:26

I have 2 table, that is a question_table and answer_table the structure is like this :

And I have a JSON array that I got from question_table and answer_table using php

相关标签:
2条回答
  • 2021-01-29 00:00

    Can you try following code:

    $sql = "select q.id, q.question, a.aswer from question_table q inner join answer_table a ON q.id = a.id_question”;
    $resultPertanyaan = mysqli_query($con, $sql);
    
    while($rowQuery= mysqli_fetch_array($resultPertanyaan)){
       $array_result[]= 
    array('id'=>$rowQuery['id’],’question’=>$rowQuery['question'], 'answer' => $rowQuery['aswer']);
    }
    
    0 讨论(0)
  • 2021-01-29 00:02

    You can use array_map to process each of the questions, looking for an answer in $array_answer for each one:

    $questions = json_decode($array_question);
    $answers = json_decode($array_answer, true);
    
    $array_result = array_map(function ($v) use ($answers) {
        $v->answer = ($k = array_search($v->id, array_column($answers, 'id_question'))) !== false ? $answers[$k]['answer'] : null;
        return $v;
    }, $questions);
    print_r(json_encode($array_result, JSON_UNESCAPED_SLASHES));
    

    Output:

    [{"id":"8","question":"Shop sign/billboard ","answer":null},
     {"id":"10","question":"Pylon","answer":null},
     {"id":"11","question":"Banner","answer":"1"},
     {"id":"12","question":"Sport","answer":"3"},
     {"id":"14","question":"Matic ","answer":"1"},
     {"id":"16","question":"Cub","answer":"3"}
    ]
    

    Demo on 3v4l.org

    Update

    For versions of PHP prior to 5.4, there are a couple of issues with the above code. Firstly array_column was not implemented in PHP until version 5.5.0. Secondly the JSON_UNESCAPED_SLASHES constant and associated functionality wasn't implemented until PHP 5.4.0. We can emulate those with this code:

    function my_array_column($array, $column) {
        return array_map(function ($v) use ($column) { return $v[$column]; }, $array);
    }
    
    $array_result = array_map(function ($v) use ($answers) {
        $v->answer = ($k = array_search($v->id, my_array_column($answers, 'id_question'))) !== false ? $answers[$k]['answer'] : null;
        return $v;
    }, $questions);
    echo str_replace('\/', '/', json_encode($array_result));
    

    Demo on 3v4l.org

    0 讨论(0)
提交回复
热议问题