2014-01-21 78 views
1

我下面就tutplus this tutorial,我碰到这个代码片段传来:这是一个PHP关联数组吗?

//check if the action exists in the controller. if not, throw an exception. 
    if(method_exists($controller, $action) === false) { 
     throw new Exception('Action is invalid.'); 
    } 

    //execute the action 
    $result['data'] = $controller->$action(); 
    $result['success'] = true; 

} catch(Exception $e) { 
    //catch any exceptions and report the problem 
    $result = array(); 
    $result['success'] = false; 
    $result['errormsg'] = $e->getMessage(); 
} 

//echo the result of the API call 
echo json_encode($result); 
exit(); 

我在PHP初学者,我在想,如果result是一个关联数组?有人可以证实这一点吗?如何才能说明关联数组和非关联数组之间的区别?

+1

是。因为您要为数组中的每个元素提供一个键名。 – Drumbeg

+1

它是一个关联数组。它将键值“sucess”,“errormsg”与值相关联。 –

+5

我建议阅读文档。 http://uk3.php.net/manual/en/language.types.array.php – Drumbeg

回答

2

$result是一个关联数组,因为您分配了一个键名。

“正常”数组没有键名。

4

要检查关联数组或没有,你可以使用此功能

function is_assoc($var) 
    { 
      return is_array($var) && array_diff_key($var,array_keys(array_keys($var))); 
    } 

    function test($var) 
    { 
      echo is_assoc($var) ? "I'm an assoc array.\n" : "I'm not an assoc array.\n"; 
    } 

    // an assoc array 
    $a = array("a"=>"aaa","b"=>1,"c"=>true); 
    test($a); 
+0

这是一种极大的方式让初学者进行更多的自学,因为他们开始想知道这些功能是做什么的。 –

+0

是的。你从另一个角度来到这里好吗? – Drumbeg