我正在阅读PHP中的三元和空合并运算符,并进行了一些实验。
所以,与其写
if (isset($array['array_key']))
{
$another_array[0]['another_array_key'] = $array['array_key'];
}
else
{
// Do some code here...
}而不是用空合并或三值运算符缩短代码,而是尝试使用空合并来进一步缩短代码,但没有“否则”部分,因为我并不真正需要。我搜索了一下,找到了一些我不想要的解决方案。
我试过了,这两种解决方案都奏效了!
$another_array[0]['another_array_key'] = $array['array_key'] ??
$another_array[0]['another_array_key'] = $array['array_key'] ? :
print_r($another_array);注:没有;在上面一行的末尾。
我的问题是:这是一个可以接受的代码吗?我认为这可能很难用评论来解释,因为过了一段时间,它可能成为可读性的负担。
对不起,如果这是一个类似的问题-我没有真正的时间来检查他们的所有,因为有相当多的建议堆栈溢出。
这将是一个“完整的”代码示例:
<?php
$another_array = [];
$array = [
'name' => 'Ivan The Terrible',
'mobile' => '1234567890',
'email' => 'tester@test.com'
];
if (isset($array['name']))
{
$another_array[0]['full_name'] = $array['name'];
}
$another_array[0]['occupation'] = $array['occupation'] ??
// or $another_array[0]['occupation'] = $array['occupation'] ? :
print_r($another_array);发布于 2020-01-17 13:25:57
可维护性..。如果您想测试许多可能的数组键,然后将它们添加到最后的数组中,那么没有什么可以阻止您创建第三个数组,该数组将保存键以检查并循环通过该数组:
<?php
$another_array = [];
$array = [
'name' => 'Ivan The Terrible',
'mobile' => '1234567890',
'email' => 'tester@test.com'
];
$keysToCheck = [
// key_in_the_source_array => key_in_the_target
'name' => 'full_name',
'occupation' => 'occupation'
// if you want to test more keys, just add them there
];
foreach ($keysToCheck as $source => $target)
{
if (isset($array[$source]))
{
$another_array[0][$target] = $array[$source];
}
}
print_r($another_array);请注意
$another_array[0]['occupation'] = $array['occupation'] ??
print_r($another_array);被评估为
$another_array[0]['occupation'] = $array['occupation'] ?? print_r($another_array);如果在后面添加另一个print_r($another_array);,您会注意到$another_array[0]['occupation'] => true是因为the return value of print_r()
https://stackoverflow.com/questions/59787912
复制相似问题