数组元素在 PHP 中添加的数组元素不一致,数组 += 数组



这可能是一个愚蠢的问题,但我很难弄清楚为什么这并不总是有效。 我初始化一个数组,然后传递一些向数组添加另一个元素的 if 语句。 这似乎在大多数情况下都有效,但有时即使 if 语句为 true,也不会添加元素。 下面是一些代码:

$data = array ("command" => "/order/list", "account_id" => Config::get('DEFAULT_ACCOUNT_ID'));
if (isset($post['data-mrn']) && $post['data-mrn'] != '' ) {
$data += array("filter.patientid.equals" => $post['data-mrn']);
}
if (isset($post['data-name']) && $post['data-name'] != '' ) {
$data += array("filter.patient_name.like" => '');
}
if (isset($post['data-accession']) && $post['data-accession'] != '' ) {
$data += array("filter.accession_number.equals" =>$post['data-accession']);
}
if (isset($post['data-description']) && $post['data-description'] != '') {
$data += array("filter.customfield-421250f4-ea28-42b2-b53d-06ba84f16d36.like" => 'xxx');
}
if (isset($post['data-modality']) && $post['data-modality'] != '' ) {
$data += array("filter.customfield-421250f4-ea28-42b2-b53d-06ba84f16d36.like" => 'xxx');
}
if (isset($post['data-status']) && $post['data-status'] != '') {
$data += array("filter.customfield-421250f4-ea28-42b2-b53d-06ba84f16d36.like" => 'xxx');
}
if (isset($post['data-date']) && $post['data-date'] != '' ) {
$post['data-date'] = str_replace("-","",$post['data-date']);
$data += array("filter.customfield-421250f4-ea28-42b2-b53d-06ba84f16d36.like" => 'xxx');
print_r($data );
}

如果我传入 mn、accession_number、状态和日期,我会得到:

阵列 ( [命令] =>/订单/列表 [account_id] => xxx [filter.patientid.equals] => xxx [filter.accession_number.等于] => xxx [filter.customfield-421250f4-ea28-42b2-b53d-06ba84f16d36.like] => xxx )

并且它省略了日期,即使 print_r($data( 位于日期的 if 语句中, 所以数据 += 没有添加该条件。 还有其他组合,即使它满足 if 条件,它也不会更新 $data 数组。 只是想知道是否有更好的方法来做到这一点以及为什么会发生这种情况。

filter.customfield-421250f4-ea28-42b2-b53d-06ba84f16d36.like使用相同的密钥四次。关联数组必须具有唯一键。您不能这样做:

$array = [
'foo' => 'bar1',
'foo' => 'bar2',
'foo' => 'bar3',
];

如果你有这个:

$array = [
'foo' => 'bar1',
];

然后尝试合并包含现有键的数组,

$array += [
'foo' => 'bar2',
];

PHP 将丢弃重复的项目,因为密钥已经存在。

如果您改为这样做:

$array = [
'foo' => 'bar1',
];
$array['foo'] = 'bar2';

然后 PHP 会用新值覆盖现有键,这也不是你想要的。

因此,如果要维护指定的所有值,则需要使用唯一键:

$array = [
'foo1' => 'bar1',
'foo2' => 'bar2',
'foo3' => 'bar3',
];

或者使用索引数组:

$array = [
'bar1',
'bar2',
'bar3',
];

或者也许(花哨!(关联数组中的索引数组:

$array = [
'foo' => [
'bar1',
'bar2',
'bar3',
],
];

最新更新