gpt4 book ai didi

javascript - 通过php发送两个变量到js

转载 作者:行者123 更新时间:2023-12-02 21:19:02 26 4
gpt4 key购买 nike

我有

$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
}
}

如何在 echo json_encode($count); 上发送 2 个变量,以便双重检查“ID 是否在数组中?数组是否小于 2?” 还是我缺少另一种方式?

最佳答案

简单的方法是使用 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));
}

关于javascript - 通过php发送两个变量到js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60898020/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com