1

我的项目在 cakePHP 中,但我认为这是我误解的原生 PHP 的一个方面。

afterFind($results, $primary = false)AppModel. debug($results);如果我得到一个这样的数组,在一个特定的发现上

array(
    'id' => '2',
    'price' => '79.00',
    'setup_time' => '5',
    'cleanup_time' => '10',
    'duration' => '60',
    'capacity' => '1',
    'discontinued' => false,
    'service_category_id' => '11'
)

在我的afterFind我有一些这样的代码:

foreach($results as &$model) {
  // if multiple models
  if(isset($model[$this->name][0])) {
    ....

查找的结果来自我的Service模型,因此插入该 for$this->name并检查if(isset($model['Service'][0]))应该返回 false,但它返回 true?if(isset($model['Service']))按预期返回 false。

我收到以下 PHP 警告:

非法字符串偏移“服务”

那么这里发生了什么?if(isset($model['Service'][0]))如果返回false ,为什么返回if(isset($model['Service']))true?

更新:

我仍然不知道我原来的问题的答案,但我通过首先检查 $results 是否是一个多维数组来解决它

if(count($results) != count($results, COUNT_RECURSIVE))

4

2 回答 2

1

使用array_key_exists()orempty()代替isset(). PHP 奇怪地缓存旧数组值。他们必须使用手动取消设置unset()

isset() 不会为对应于 NULL 值的数组键返回 TRUE,而array_key_exists()会。

于 2013-09-11T19:12:19.870 回答
0

字符串偏移量提供了一种机制来使用字符串,就好像它们是一个字符数组一样:

$string = 'abcde';
echo $string[2]; // c

$model确实是除终止之外的所有键的字符串。

至于isset($model['Service'][0])返回值,我有点意外。这是一个简化的测试用例:

$model = '2';
var_dump(isset($model['Service'])); // bool(false)
var_dump(isset($model['Service'][0])); // bool(true)

一定是有原因的。会挖的。。

于 2013-09-11T19:11:15.123 回答