如何在php中按键和值分隔数组

时间:2016-02-17 06:52:21

标签: php arrays

我的数组

Array ( [0] => stdClass Object ( [ProductInfo] => Prouduct 1  [Dept] => 01 [MarkOnTimeShipment] => 0 ) [1] => stdClass Object ( [ProductInfo] => Prouduct 2 [MarkOnTimeShipment] => 0 ) [2] => stdClass Object ( [ProductInfo] => Prouduct 2 [MarkOnTimeShipment] => 1 )  [3] => stdClass Object ( [ProductInfo] => Prouduct 2 [MarkOnTimeShipment] => 0 )  [4] => stdClass Object ( [ProductInfo] => Prouduct 2 [MarkOnTimeShipment] => 1 ) 

我现在有一些像上面这样的数组我想要得到的是有两个值,如下所示。我需要将它分开并将其作为数组

已过滤的输出

MarkOnTimeShipment = 1 是一个隔离数组

  Array ( [0] => stdClass Object ( [ProductInfo] => Prouduct 1  [Dept] => 01 [MarkOnTimeShipment] => 0 ) [1] => stdClass Object ( [ProductInfo] => Prouduct 2 [MarkOnTimeShipment] => 0 )    [2] => stdClass Object ( [ProductInfo] => Prouduct 2 [MarkOnTimeShipment] => 1 ) 

MarkOnTimeShipment = 0 是一个隔离数组

Array ( [0] => stdClass Object ( [ProductInfo] => Prouduct 1  [Dept] => 01 [MarkOnTimeShipment] => 0 ) [1] => stdClass Object ( [ProductInfo] => Prouduct 2 [MarkOnTimeShipment] => 0 ) 

2 个答案:

答案 0 :(得分:1)

您可以通过 MarkOnTimeShipment 键将数组分隔为

$newArr = array();
foreach ($array as $key => $value) {
    $newArr[$value->MarkOnTimeShipment][] = $value;
}
echo "<pre>";
print_r($newArr);

$array1 = $newArr[0]; // MarkOnTimeShipment = 0 
$array2 = $newArr[1]; // MarkOnTimeShipment = 1  

$ array1的结果(MarkOnTimeShipment = 0):

Array
(
    [0] => stdClass Object
        (
            [ProductInfo] => Prouduct 1
            [Dept] => 1
            [MarkOnTimeShipment] => 0
        )

    [1] => stdClass Object
        (
            [ProductInfo] => Prouduct 3
            [MarkOnTimeShipment] => 0
        )

)

$ array2的结果(MarkOnTimeShipment = 1):

Array
(
    [0] => stdClass Object
        (
            [ProductInfo] => Prouduct 2
            [MarkOnTimeShipment] => 1
        )

    [1] => stdClass Object
        (
            [ProductInfo] => Prouduct 4
            [MarkOnTimeShipment] => 1
        )

)

答案 1 :(得分:0)

有两个不同的函数可用于键和值array_keys和array_values。请试一试。

$array_keys = array_keys($array);
$array_values = array_values($array);