你如何迭代Input :: post()数据?

问题描述 投票:0回答:2

据我所知,没有参数的Input::post();返回一个包含特定POST的所有数据的数组。

我正在做这个$all_input = Input::post();

但后来我在类似Java的数组中进行迭代(你是怎么做到的?)

for ($i=0; $i<count($all_input); $i++)
    { 
        if (strpos($all_input[$i], 'something') == true) // ERROR...

但应用程序崩溃与错误Undefined offset: 0,我认为这意味着没有找到索引?

我也尝试添加这个无济于事:

    if (!isset($all_input))
    {
        return;
    }

如果是这样,您如何访问数据以迭代它们?我知道它包含数据因为我可以在浏览器调试期间按下按钮时看到它们,如果我删除该代码。

如果你还没弄清楚我是从Java开发人员那里来的,我刚刚开始学习php,所以请耐心等待。

php fuelphp
2个回答
1
投票

根据这个:https://fuelphp.com/docs/classes/input.html#/method_post Input::post();将返回$_POST这是一个关联数组。这是源代码,因为fuelphp的文档没有完全涵盖它。

/**
 * Fetch an item from the POST array
 *
 * @param   string  $index    The index key
 * @param   mixed   $default  The default value
 * @return  string|array
 */
public static function post($index = null, $default = null)
{
    return (func_num_args() === 0) ? $_POST : \Arr::get($_POST, $index, $default);
}

你需要引用你的输入名称,所以如果你有一个你称之为“名字”的输入,那么你需要引用$all_input['name']。您可以使用array_keys()函数获取密钥。如果你在这种情况下使用foreach也更好。喜欢:

foreach($all_input as $key => $value) {
    echo 'Input key: ' . $key . ' value: ' . $value;
}

如果你离开了$key =>你将只获得价值,你可以离开它,如果你不在foreach中使用它。

如果你不想使用foreach,为什么:

$all_input = Input::post();
$keys = array_keys($all_input);
for ($i = 0; $i < count($keys); $i++) {
    if (strpos($all_input[$keys[$i]], 'something') == true) {
        // Do your stuff here.
    }
}

但是我仍然建议尽可能使用foreach,它的开销更少,代码也更清晰。


0
投票

这不起作用,因为您正在处理对象(输入)而不是数组。

我建议使用foreach循环副循环。要验证输入对象的内容/结构,您还可以执行dd()以完整地查看输入对象。

基本上,

$input = Input::post();

foreach($input as $i) {

    echo $i;  //this is a property of the Input Object.  if you have arrays or other objects store inside of it, you may need to go deeper into the oject either with a foreach loop again or by calling the property directly ($i->property)

};
© www.soinside.com 2019 - 2024. All rights reserved.