我在PHP中有一个关联数组
$a = array("d1" => "data", "d2" => NULL, "d3" => "data")
我想得到所有键和所有不为NULL的值,以便内爆它们:
// e.g.:
$sub_key = array_keys($a, keys != NULL);
$sub_values = array_values($a, values != NULL);
echo "`".implode("`,`", $sub_key)."`";
echo "'".implode("','", $sub_key)."'";
是否有array_keys()
和array_values()
这样的功能,只允许使用不匹配模式的视图?
答案 0 :(得分:2)
在使用array_keys之前使用array_filter并像这样过滤数组
$newArray = array_filter($a);
然后做
$sub_key = array_keys($newArray);
$sub_values = array_values($newArray);
答案 1 :(得分:1)
您可以使用array_filter($a)
,但正如上面提到的其中一条评论所指出的,这也会过滤掉FALSE,空字符串等值。所以我会使用foreach循环。
$new_array = array();
foreach ($a as $key => $value) {
if (is_null($value) === false) {
$new_array[$key] = $value;
}
}
答案 2 :(得分:1)
$a = array("d1" => "data1", "d2" => NULL, "d3" => "data3");
$b = array_filter($a); // Not Null Values Array
$sub_key = array_keys(array_filter($a));
$sub_values = array_values(array_filter($a));
echo "`".implode("`,`", $sub_key)."` <br/>";
echo "'".implode("','", $sub_values)."'";
答案 3 :(得分:0)
$sub_key = array();
$sub_values = array();
foreach ($a as $key => $value) {
if (!is_null($key) && !is_null($value)) { // you can also do is_empty() in stead of is_null() if you also wan't to avoid empty string
$sub_key[] = $key;
$sub_values[] = $value; // or use mysql_real_escape_string($value) if you are going to create a query with this! Otherwise you will create an SQL injection vulnerability here.
}
}
// you can add if(count($sub_key)) here to only do the echoes, if there was at least 1 item in the array. Otherwise you will echo an empty ``
echo "`".implode("`,`", $sub_key)."`";
echo "'".implode("','", $sub_key)."'"; // don't you mean $sub_values here?
答案 4 :(得分:0)
请尝试以下操作:
// Loop to find empty elements and
// unset the empty elements
foreach($array as $key => $value)
if(empty($value))
unset($array[$key]);
// Display the array elements
foreach($array as $key => $value)
echo ($array[$key] . "<br>");
在这种情况下,您将$ array替换为$ a。这将适用于空/空键值。