Pie*_*ing 48 php arrays coding-style
在php中,我经常需要使用数组来映射变量......但我似乎无法在一个内联中执行此操作.cf示例:
// the following results in an error:
echo array('a','b','c')[$key];
// this works, using an unnecessary variable:
$variable = array('a','b','c');
echo $variable[$key];
Run Code Online (Sandbox Code Playgroud)
这是一个小问题,但它每隔一段时间就会不停地窃听......我不喜欢这样一个事实:我没有使用变量;)
Joh*_*hat 38
技术答案是PHP语言的语法只允许在变量表达式的末尾使用下标符号而不是通常的表达式,这就是它在大多数其他语言中的工作方式.我一直把它看作是语言的缺陷,因为有可能有一个语法可以明确地解析任何表达式的下标.然而,可能的情况是,他们使用的是不灵活的解析器生成器,或者他们根本不想破坏某种向后兼容性.
以下是有效表达式上无效下标的几个示例:
$x = array(1,2,3);
print ($x)[1]; //illegal, on a parenthetical expression, not a variable exp.
function ret($foo) { return $foo; }
echo ret($x)[1]; // illegal, on a call expression, not a variable exp.
Run Code Online (Sandbox Code Playgroud)
Mbr*_*vda 23
这称为阵列解除引用.它已在PHP 5.4中添加. http://www.php.net/releases/NEWS_5_4_0_alpha1.txt
更新[2012-11-25]:从PHP 5.5开始,解除引用已被添加到容器/字符串以及数组中
onn*_*odb 16
真的,我不会为那个额外的变量而烦恼.但是,如果您愿意,也可以在使用它之后将其从内存中删除:
$variable = array('a','b','c');
echo $variable[$key];
unset($variable);
Run Code Online (Sandbox Code Playgroud)
或者,你可以编写一个小函数:
function indexonce(&$ar, $index) {
return $ar[$index];
}
Run Code Online (Sandbox Code Playgroud)
并称之为:
$something = indexonce(array('a', 'b', 'c'), 2);
Run Code Online (Sandbox Code Playgroud)
现在应该自动销毁该数组.
小智 5
这可能没有直接关系.但是我找到了这个特定问题的解决方案.
我从以下形式的函数中得到了一个结果.
Array
(
[School] => Array
(
[parent_id] => 9ce8e78a-f4cc-ff64-8de0-4d9c1819a56a
)
)
Run Code Online (Sandbox Code Playgroud)
我想要的是parent_id值"9ce8e78a-f4cc-ff64-8de0-4d9c1819a56a".我使用了这样的功能并得到了它.
array_pop( array_pop( the_function_which_returned_the_above_array() ) )
Run Code Online (Sandbox Code Playgroud)
所以,它是在一行完成的:)希望它会对某人有所帮助.