基本上按照标题。下面的代码很好地工作,但似乎是一个相当漫长的过程来做什么似乎是一个相当简单的任务。有没有一种更有效的方法来根据已经存在于数组中的内容来插入新的数组变量
我会看看foreach是如何工作的,但我想知道是否真正正确地解决了这个问题。
编辑:例如,我看到人们使用“{}”来连接而不是“。”。说它速度更快,但我一直无法让他们在这段代码中工作。
<?php
// Create Array
$foobar = array(
"foo" => "test1",
"bar" => "hello",
"far" => "this",
"boo" => "is",
// "foo_result" => "", // Uncomment to check that function does nothing where foo_result already available
"foo_link" => "http://1.media.collegehumor.cvcdn.com/82/16/162e153d618d49869783ccd475005fd5.jpg",
"for" => "cool"
);
function _insertarray($foobar) {
// provide arrays to test against
$foo1 = array("test1","test2");
$foo2 = array("test3","test4");
$foo3 = array("test5","test6");
$foo4 = array("test7","test8");
// End function where "foo_result" is already set
if (isset($foobar['foo_result'])) {
// Nothing to do
}
else {
// add the variable to the foo_result index based on values returned
if ((count(array_intersect($foo1, $foobar))) ? true : false) {
$foobar['foo_result'] = "<iframe src='" . $foobar["foo_link"] . "'>";
}
else if ((count(array_intersect($foo2, $foobar))) ? true : false) {
$foobar['foo_result'] = "<a href='" . $foobar["foo_link"] . "'>";
}
else if ((count(array_intersect($foo3, $foobar))) ? true : false) {
$foobar['foo_result'] = "<img src='" . $foobar["foo_link"] . "'>";
}
else if ((count(array_intersect($foo4, $foobar))) ? true : false) {
$foobar['foo_result'] = "<iframe src='" . $foobar["foo_link"] . "'>";
}
else {
// Nothing to do here
}
}
return $foobar;
}
print_r(_insertarray($foobar));
?>
在此先感谢
只是为了澄清,你的意思是'CPU时间短'或'更短/更好的代码'有效' – Patashu 2013-04-21 04:12:24
为什么你写'if(blah?true:false)'而不是'if(blah )'? – Barmar 2013-04-21 04:16:23
@Patashu我的意思是减少CPU时间,并且如果它导致代码更短,那么它会带来奖励。 – user1937392 2013-04-21 04:20:43