dongqiao8417 2012-10-20 05:16
浏览 6

如何评估数组中的每个值都是真的并在这种情况下在Php中做一些事情?

I need to insert more than one row in a table

foreach($answers as $answer){
  $sql =<<<EOD
  INSERT INTO answer(`answer`, `question_id`) 
  VALUES ('$answer', (SELECT `id` FROM question WHERE `title` = '$title'))
  EOD;

  result_array[] = $this->db->query($sql);  
}   

I need to check each insert query is return True. What's control structure in Php can let me do something like:

if(each_value in result_array == 'True'){
  return 'success';
}
  • 写回答

2条回答 默认 最新

  • drcb19700 2012-10-20 05:25
    关注

    To make sure that you only have booleans in your array double negate the values returned by your query function (unless it already returns true/false, of course).:

    result_array[] = !! $this->db->query($sql);
    

    Alternative #1

    You could find the unique values between array(true) and your resulting array (result_array) and then see if the size is equal to zero using array_diff:

    if (sizeof (array_diff (result_array, array (true)) == 0) {
      // all went well
    }
    

    Alternative #2

    If your resulting array only consists of values of either true or false you could hack your way through it using array_product such as in the below:

    var_dump (array_product (array (true, false, true)));
    var_dump (array_product (array (true, true, true)));
    

    Output

    int(0)
    int(1)
    

    array_product will multiply all the values of the array with each other, and since true evalutes to the integer 1 and false to the integer 0 we can use this to our advantage.



    Alternative #3 (don't modify source array)

    You could use array_reduce with a callback to reduce your array to a single value, such as:

    if (array_reduce (result_array, function ($a,$b) {return $a && $b;}, true) == true) {
      // all went well
    }
    

    This will implicitly cast every value of your array to a boolean, and give you the result you are after.

    inline lambdas require more recent versions of PHP, a regular function name can be used as a callback if lambdas are unavailable

    评论

报告相同问题?