skip to Main Content

Here is function:

protected function get_answers_with_question_id($id){
    global $wpdb;

    $sql = "SELECT *
            FROM {$wpdb->prefix}aysquiz_answers
            WHERE question_id=" . $id;

    $answer = $wpdb->get_results($sql, 'ARRAY_A');

    return $answer;
}

Call function:

    foreach ($questions_ids as $id) {
        
    $answers2[] = $this->get_answers_with_question_id2($id);
        
    }

Actual output:

[[{"answer":"1000"}],[{"answer":"1000"}],[{"answer":"1000"}]]

I need classic array: array(key=>value,key=>value,key=>value,etc.)

2

Answers


  1. Chosen as BEST ANSWER

    Thank you.

    questions_ids is in format: ["3","4","5"]

    But it returns null:

    $answers2 = $this->get_answers_with_question_ids($questions_ids)[0];
    

    If i edit to:

    $answers2 = $this->get_answers_with_question_ids($questions_ids);
    Return: [{"answer":"1005"}]
    

  2. In terms of performance improvements, you can use the IN operator in the query.

    Taking the full array, you cancel implode() this, taking each of the values in the array, and adding them into a comma separated list, within the brackets in the query.

    This should return all the values you would have got from looping through and getting them one by one, but without the overhead:

    protected function get_answers_with_question_ids($questions_ids){
    global $wpdb;
    
    $sql = "SELECT *
            FROM {$wpdb->prefix}aysquiz_answers
            WHERE question_id IN (" . implode(',', $questions_ids) . ")";
    
    $answer = $wpdb->get_results($sql, 'ARRAY_A');
    
    return $answer;
    }
    

    This change, and perhaps also not creating an array and just assigning the result directly on $answers2, should get you the format you want:

    $answers2 = $this->get_answers_with_question_ids($questions_ids)[0];
    
    // Should return something like [{"answer":"1000"},{"answer":"1000"},{"answer":"1000"}]?
    
    foreach ($answers2 as $a) {
        echo $a.answer // "1000" x 3
    }
    

    Consider also looking into securing your SQL queries, with it being integers/ids, it should be fine, though, really you want to be santising and escaping any values you use in queries, ESPECIALLY, if the user can adjust the query with their input.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search