我有一個函式可以根據競賽的獲獎條目串列檢查用戶提交的值。
目前,如果用戶輸入“1234”,它會回傳 false,即使該值存在,但如果用戶輸入“5678”,它會回傳 true 并發送回與該條目關聯的所有資料。
有人能指出為什么它只找到陣列中的最后一個值是真的嗎?我嘗試了幾種不同的方法,但沒有任何效果!
$entries = array(
(object) [
"uid" => "1234",
"item" => "x",
"text_prefix" => "x",
"text_suffix" => "x",
"prize_link" => "x",
"data_captcher" => true
],
(object) [
"uid" => "5678",
"item" => "x",
"text_prefix" => "x",
"text_suffix" => "x",
"prize_link" => "x",
"data_captcher" => false
],
);
// $data = json_encode($entries);
// echo $data;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$code = isset($_POST['code']) ? $_POST['code'] : '';
var_dump($code);
// foreach ($entries as $entry => $entry_Value) {
for ($x = 0; $x < count($entries); $x ) {
// var_dump($entry->uid);
if ($entries[$x]->uid == $code) {
$value = [
"uid" => $entries[$x]->uid,
"item" => $entries[$x]->item,
"text_prefix" => $entries[$x]->text_prefix,
"text_suffix" => $entries[$x]->text_suffix,
"prize_link" => $entries[$x]->prize_link,
"data_captcher" => $entries[$x]->data_captcher,
];
}else {
$value = 'false';
}
// var_dump($entries[$x]);
}
$data = json_encode($value);
echo $data;
}
uj5u.com熱心網友回復:
這很簡單,你錯過了一個停止條件。
您的回圈會迭代所有條目,因此最后一個條目將確定是否value為假。
你應該做的是break在你的if條件中添加:
if ($entries[$x]->uid == $code) {
$value = [
"uid" => $entries[$x]->uid,
"item" => $entries[$x]->item,
"text_prefix" => $entries[$x]->text_prefix,
"text_suffix" => $entries[$x]->text_suffix,
"prize_link" => $entries[$x]->prize_link,
"data_captcher" => $entries[$x]->data_captcher,
];
break; // <== this will stop the "for" loop
}else {
$value = 'false';
}
順便說一句,在您的情況下,foreach出于可讀性原因,我會使用回圈:
foreach ($entries as $entry) {
:
:
}
uj5u.com熱心網友回復:
當您找到匹配項時,您并沒有停下來。下一次迭代是不匹配的,所以你最終會回傳一個 false。當您找到匹配項時,您需要停止回圈,您可以使用break;
也是foreach一個比一個更簡單的回圈for
此外,當您找到正確的物件時,您無需完成所有這些任務,只需執行 a 就可以了$value = $entry_obj;。
$entries = array(
(object) [
"uid" => "1234",
"item" => "x",
"text_prefix" => "x",
"text_suffix" => "x",
"prize_link" => "x",
"data_captcher" => true
],
(object) [
"uid" => "5678",
"item" => "x",
"text_prefix" => "x",
"text_suffix" => "x",
"prize_link" => "x",
"data_captcher" => false
],
);
$data = json_encode($entries);
$_POST['code'] = '1234';
$code = isset($_POST['code']) ? $_POST['code'] : '';
var_dump($code);
foreach ($entries as $entry_obj) {
if ($entry_obj->uid == $code) {
$value = $entry_obj;
break; // found it so stop otherwise we dont find it on next iteration
}else {
$value = 'false';
}
}
$data = json_encode($value);
echo $data;
結果
{
"uid":"1234",
"item":"x",
"text_prefix":"x",
"text_suffix":"x",
"prize_link":"x",
"data_captcher":true
}
uj5u.com熱心網友回復:
對于更簡單的解決方案,您可以使用array_column和空合并運算子的組合。
// First re-key the array so that uid is the key
$entries = array_column($entries, null, 'uid');
// Then you can check if the array key exists directly, and assign a default value if not
$value = $entries[$code] ?? 'false';
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/365917.html
標籤:php
