Is there a method to pivot an array of 2 key value pairs to a single key value?

时间:2018-02-03 10:24:35

标签: php arrays

When pulling information from a table, you can usually get :

Field1  |  Field2
=================
ValueX  |  ValueY
ValueA  |  ValueB

Which when retrieved, ends up as :

array(
    array(
           "Field1"=>"ValueX",
           "Field2"=>"ValueY"
    ),
    array(
           "Field1"=>"ValueA",
           "Field2"=>"ValueB"
    )
)

What I would like to do, is flip the array around so it becomes this:

array(
     "ValueX"=>"ValueY",
     "ValueA"=>"ValueB"
)

Is there any built in way to do this in PHP, and If not, what would be the most resource friendly approach to getting this done ?

2 个答案:

答案 0 :(得分:1)

Not sure if it's a typo in your expected output(ValueX for both results), but using array_column can convert the array to be how you want it...

$array1 = array(
    array(
        "Field1"=>"ValueX",
        "Field2"=>"ValueY"
    ),
    array(
        "Field1"=>"ValueA",
        "Field2"=>"ValueB"
    )
);

$array2 = array_column($array1, "Field2", "Field1");
print_r($array2);

gives...

Array

(
    [ValueX] => ValueY
    [ValueA] => ValueB
)

答案 1 :(得分:1)

尝试使用此方法来获取数组而不使用键(列名称):

$result=array();
foreach ($array as $subarr){
  $arr = array_values($subarr);
  $result[$arr[0]] = $arr[1];
}
var_dump($result);

输出:

array(2) { ["ValueX"]=> string(6) "ValueY" ["ValueA"]=> string(6) "ValueB" }