douhui1630 2012-09-13 11:12
浏览 23
已采纳

如何在php中将数组分组到一个数组中?

I would like to convert / form the following arrays as example:

Array ( [product_category] => for-women ) Array ( [brand] => 7-diamonds ) Array ( [size] => 12 ) Array ( [color] => 882536 )

Into one array that just merges each array pair and put them altogether :

Array ( [product_category] => for-women [brand] => 7-diamonds [size] => 12 [color] => 882536 )

I tried array_merge and it didn't work. The array out put in my code is from $_SESSION which returns an array (a pair key=> value) like this:

foreach($_SESSION as $k => $v) {
    if (strstr($k, 'saved_query_') == true) {
        $saved = array_merge($v);
    }
}

So I get each array by looping through session which has a query, the result is array pair, I want to combine all pairs found (Do not know how to use array_merge in that case).

I tried array_combine and array_merge they do not seem like the functions I need based on php manual:

array_combine — Creates an array by using one array for keys and another for its values

Which I do not want to do, I just want to copy/move small arrays in one array, without changing any pairing/key/value.

  • 写回答

4条回答 默认 最新

  • doulaobi7988 2012-09-13 11:17
    关注

    You can try using 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);
    

    Output

    Array ( [product_category] => for-women [brand] => 7-diamonds [size] => 12 [color] => 882536 )
    

    See Demo

    * ----- Update ----- *

    If you are looking through a session

    $_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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值