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

    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值