我有一个
$_SESSION
数组,我通过循环内的键对其进行过滤/清理。
这会生成一个合格数据的二维数组,但我想将其简化为平面关联数组。
理论输入:
$_SESSION = [
// ...some unwanted row
'saved_query_something' => ['product_category' => 'for-women'],
'saved_query_something_else' => ['brand' => '7-diamonds'],
// ...some unwanted row
'saved_query_blah' => ['size' => 12],
'saved_query_blar' => ['color' => 882536],
];
这是我当前的代码,在清理时没有正确减少数据结构。
foreach ($_SESSION as $k => $v) {
if (strstr($k, 'saved_query_') == true) {
$saved = array_merge($v);
}
}
想要的结果:
[
'product_category' => 'for-women',
'brand' => '7-diamonds',
'size' => 12,
'color' => 882536,
]
您可以尝试使用array_merge
$array0 = Array ( "product_category" => "for-women" );
$array1 = Array ( "brand" => "7-diamonds" ) ;
$array2 = Array ( "size" => "12" ) ;
$array3 = Array ( "color" => "882536" );
$array = array_merge($array0,$array1,$array2,$array3);
print_r($array);
输出
Array ( [product_category] => for-women [brand] => 7-diamonds [size] => 12 [color] => 882536 )
* ----- 更新 ----- *
如果您正在浏览会话
$_SESSION = Array();
$_SESSION[0] = Array("product_category" => "for-women");
$_SESSION[1] = Array("brand" => "7-diamonds");
$_SESSION[2] = Array("size" => "12");
$_SESSION[3] = Array("color" => "882536");
$final = array();
foreach ( $_SESSION as $key => $value ) {
$final = array_merge($final, $value);
}
print_r($final);
$result = array_merge_recursive($ar1, $ar2 [, array $...]);
请使用
array_merge
来代替。
$ret = array_merge($arr1, $arr2, $arr3);
使用您的代码,您应该这样做:
$saved = array_merge($saved, $v);
您应该看看 PHP 中的 array_merge() 函数:http://php.net/manual/en/function.array-merge.php
简单使用如下:
$array1 = Array ( [product_category] => for-women );
$array2 = Array ( [brand] => 7-diamonds );
$array3 = Array ( [size] => 12 );
$array4 = Array ( [color] => 882536 );
$combined = array_merge($array1, $array2, $array3, $array4);
要按第一级前缀过滤 2d 会话数组并将有效负载减少为平面关联数组(假设不可能发生键冲突),请在循环的条件块内使用数组联合赋值运算符 (
+=
)。 这会将每行的关联元素推入结果数组中,而不会创建不需要的深度。 即使您的行有多个元素,结果数组仍然是平坦的。
代码:(演示)
$_SESSION = [
'junk' => ['foo' => 'bar'],
'saved_query_1' => ['product_category' => 'for-women'],
'saved_query_2' => ['brand' => '7-diamonds'],
'junk2' => ['not valuable' => 'rubbish'],
'saved_query_number' => ['size' => 12],
'saved_query_11' => ['color' => 882536],
];
$saved = [];
foreach($_SESSION as $k => $v) {
if (str_starts_with($k, 'saved_query_')) {
$saved += $v;
}
}
var_export($saved);
输出:
array (
'product_category' => 'for-women',
'brand' => '7-diamonds',
'size' => 12,
'color' => 882536,
)