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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀