创建相同键的数组

时间:2018-10-26 06:35:30

标签: php arrays

我有一个数组$ produtcs,如下所示

Array
(
[0] => Array
    (
        [Sku] => 149826761     
        [Price] => 777.00
    )

[1] => Array
    (   
        [Sku] => 149826762
        [Price] => 862.00
    )

[2] => Array
    (
        [Sku] => 149826763
        [Price] => 661.00
    )
)

我必须从上面包含SKU,价格作为键的数组中制作一个数组,并收集数组中的所有SKU作为值。

3 个答案:

答案 0 :(得分:2)

使用嵌套循环可完成任意数量的键的工作:

<?php
    # The existent data.
    $data = [
        ["Sku" => 149826761, "Price" => 777.00],
        ["Sku" => 149826762, "Price" => 862.00],
        ["Sku" => 149826763, "Price" => 661.00]
    ];

    # Initialise a new array.
    $array = [];

    # Iterate over every associative array in the data array.
    foreach ($data as $element) {
        # Iterate over every key-value pair of the associative array.
        foreach ($element as $key => $value) {
           # Ensure the sub-array specified by the key is set.
           if (!isset($array[$key])) $array[$key] = [];

           # Insert the value in the sub-array specified by the key.
           $array[$key][] = $value;
        }
    }
?>

预期输出:

Array (
    [Sku] => Array (
        [0] => 149826761     
        [1] => 149826762
        [2] => 149826763
    )

    [Price] => Array (   
        [0] => 777.00
        [1] => 862.00
        [2] => 661.00
    )
)

答案 1 :(得分:0)

我相信您正在寻找array_column。

这将从数组中隔离一个列/键,并从输入数组中创建一个平面数组。

lapply(mget(ls()), View)

输出:

$new = array_column($arr, "Sku");
var_dump($new);

但是您也要在数组中输入价格。
我假设您要这样:

array(3) {
  [0]=>
  int(149826761)
  [1]=>
  int(149826762)
  [2]=>
  int(149826763)
}

要获得上述输出,您需要使用array列的第三个参数,如下所示:

array(3) {
  [149826761]=>
  string(6) "777.00"
  [149826762]=>
  string(6) "862.00"
  [149826763]=>
  string(6) "661.00"
}

答案 2 :(得分:0)

您可以使用foreach将元素按价格分组。例如:

// source data
$products = [    
    [
       'Sku' => 149826761,     
       'Price' => 777.00
    ],
    [ 
        'Sku' => 149826762,
        'Price' => 862.00
    ],
    [
        'Sku' => 149826763,
        'Price' => 661.00
    ]
];

// array grouping
$items = [];
foreach ($products as $product) {
   $key = $product['Price'];
   $items[$key][] = $product['Sku'];
}   

结果:

Array
(
    [777] => Array
        (
            [0] => 149826761
        )

    [862] => Array
        (
            [0] => 149826762
        )

    [661] => Array
        (
            [0] => 149826763
        )
)