首页 > 解决方案 > 通过php向js发送两个变量

问题描述

我有

$userPostsInt = array("22", "45", "56");

我通过 ajax 收到一个 id:

$post_id = $_POST['id'];

然后在前端我单击并发送一个 ID,我需要检查是否:

 1. the clicked ID is in the array
 2. if the array count is <= 2 if not do something

所以我尝试:

$totSaved = array();
$userPostsInt = array("22", "45", "56");
$count = count($userPostsInt);
if($count<2) {
  foreach($userPostsInt as $key=>$post){ 
    if( $post == $post_id ) { 
      foreach($userPostsInt as $idInt){ 
        array_push($totSaved, $idInt);
      }
      echo json_encode($count);
    }
  }
} else {
  echo json_encode($count); 
}

然后在ajax成功我做:

success: function(data) {
    var received = true;
    if(received) {
        if(data < 2) {
            do_something
        } else {
            do_something
        }
    } else {
        do_something else
    }
}

如何发送 2 个变量以对“数组中是否有 ID?数组是否小于 2?”echo json_encode($count);进行双重检查?还是我错过了另一种方式?

标签: javascriptphpjquery

解决方案


简单的方法是in_array()与数组输出一起使用:

$totSaved = array();
$userPostsInt = array("22", "45", "56");
$count = count($userPostsInt);

if(in_array($post_id,$userPostsInt)){
    echo json_encode(array('found'=>'yes','count'=>$count)); 
}else{
    $totSaved[] = $post_id;//add new value for next time checks
    echo json_encode(array('found'=>'no','count'=>$count)); 
}

推荐阅读