如何合并具有相同键的一个或多个嵌套数组值

时间:2016-11-12 06:48:41

标签: php arrays

我对这个概念有点迷惑

其实我有这样的数组

{
  "version": "1.0.0-*",
  "buildOptions": {
    "emitEntryPoint": true
  },

  "dependencies": {
    "Microsoft.NETCore.App": {
      "type": "platform",
      "version": "1.0.1"
    },
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.1",
    "Microsoft.AspNetCore.StaticFiles": "1.0.0",
    "Microsoft.Data.SQLite": "1.0.*",
    "ServiceStack.Core": "1.0.*",
    "ServiceStack.Interfaces.Core": "1.0.*",
    "ServiceStack.Text.Core": "1.0.*",
    "ServiceStack.Client.Core": "1.0.*",
    "ServiceStack.Common.Core": "1.0.*",
    "ServiceStack.Server.Core": "1.0.*",
    "ServiceStack.Admin.Core": "1.0.*",
    "Npgsql": "3.1.*",
    "ServiceStack.OrmLite.PostgreSQL.Core": "1.0.*",
    "ServiceStack.OrmLite.Sqlite.Core": "1.0.*"
    
  },

  "frameworks": {
    "netcoreapp1.0": {
      "imports": "dnxcore50"
    }
  }
}

最后,我得到了一个像这样的数组

    $arr = array("0"=>array("username"=>"username1"),"1"=>array("username"=>"username2"),"2"=>array("username"=>"username3"),"3"=>array("username"=>"username4"));
    echo "<pre>";print_r($arr);
    $finalArray = call_user_func_array('array_merge', $arr);
    echo "<pre>";print_r($finalArray);

但我需要所有的值,如下所示

Array
(
    [username] => username4
)

我该怎么做?..有人可以帮帮我..

谢谢,

2 个答案:

答案 0 :(得分:2)

使用array_column函数的简单解决方案(自PHP 5.5起可用):

$result = array_column($arr, 'username');

答案 1 :(得分:1)

您可以编写自己的函数来获取usernames

试试这个

<?php
function getUserNames($arr){
    $userNames = array();
    foreach ($arr as $key => $value){
        $userNames[$key] = $value["username"];
    }   
    return $userNames;
}
$arr = array("0"=>array("username"=>"username1"),"1"=>array("username"=>"username2"),"2"=>array("username"=>"username3"),"3"=>array("username"=>"username4"));
echo "<pre>";print_r($arr);
$finalArray = getUserNames($arr);
echo "<pre>";print_r($finalArray);
?>