确保PHP变量的最佳方法是数组

Izh*_*aki 0 php arrays php-5.3

我有一个javascript客户端将参数传递给服务器函数(我正在使用ExtJS Direct).有时客户端发送一个对象,有时它会发送一个对象数组.

目前我正在使用这个EnsureArray函数来确保参数是一个数组,然后我这样做foreach:

// Wraps a non array variable with an array.
function EnsureArray( &$aVar )
{
    if ( !is_array( $aVar ) )
        $var = array( $aVar );
}

function Destroy( $aRecords )
{
    // $aRecords might be a single object or an array of objects. Ensure it's wrapped as an array.        
    $this->EnsureArray( $aRecords );

    foreach ( $aRecords as $aRecord )
    {
        sql( "UPDATE Groups SET deleted = true WHERE id = $aRecord->id LIMIT 1" );
    }        

    return array(
        'success' => true,
    );
}   
Run Code Online (Sandbox Code Playgroud)

是否有一种技巧,更简洁的方式,一条线可以做同样的事情?

编辑:自发布此问题以来,我发现ExtJS有一个选项可以发送包含在数组中的所有记录.

小智 5

您可以尝试以下操作,而不是功能:

$aRecords = is_array($aRecords) ? $aRecords : array($aRecords);
Run Code Online (Sandbox Code Playgroud)