如何从PHP的JSON数组中获取通用值?

时间:2018-12-20 14:03:47

标签: php arrays json

实际上,我试图通过php从JSON数组获取通用值

我们有2个数组

$array1 = 
[
    {
        "flower_id": "1",
        "flower_price": "1",
        "flower_name": "Nelumbo"
    },
    {
        "flower_id": "2",
        "flower_price": "2",
        "flower_name": "Water"
    },
    {
        "flower_id": "3",
        "flower_price": "2",
        "flower_name": "Ladys"
    },
    {
        "flower_id": "4",
        "flower_price": "2",
        "flower_name": "Foxtail"
    },
    {
        "flower_id": "5",
        "flower_price": "2",
        "flower_name": "White"
    },
    {
        "flower_id": "6",
        "flower_price": "2",
        "flower_name": "Marigold"
    },
    {
        "flower_id": "7",
        "flower_price": "2",
        "flower_name": "Lotus"
    },
    {
        "flower_id": "8",
        "flower_price": "2",
        "flower_name": "Rhododendron"
    },
    {
        "flower_id": "9",
        "flower_price": "2",
        "flower_name": "Common"
    }]

这是数组调用$ array1 还有一个要与此数组进行比较的数组

$array2 =
[
    {
        "flower_id": "1",
        "flower_name": "Nelumbo"
    },
    {
        "flower_id": "3",
        "flower_name": "Ladys Slipper"
    },
    {
        "flower_id": "5",
        "flower_name": "White Orchid-tree"
    },
    {
        "flower_id": "9",
        "flower_name": "Common Rhododendron"
    }
]

但是我们需要与这两个数组交互,我想要这样的结果

[
{
    "flower_id": "1",
    "flower_name": "Nelumbo",
    "flower_price": "1"
},
{
    "flower_id": "3",
    "flower_name": "Ladys Slipper",
    "flower_price": "2"
},
{
    "flower_id": "5",
    "flower_name": "White Orchid-tree",
    "flower_price": "2"
},
{
    "flower_id": "9",
    "flower_name": "Common Rhododendron",
    "flower_price": "2"
}

]

如何从这两个数组中获得此结果? 我已经尝试过了,但是它只显示了通用值,但是我需要flower_price来

        $new_array = array_diff_key($array1,$array2);
        echo json_encode($supplierArray);

1 个答案:

答案 0 :(得分:2)

如果要查找公共项目,一种快速的方法是通过flower_id(使用array_column()来索引两个数组,然后执行array_intersect_key()来保留公共项目,并且因为$array1是第一个数组,它将保留该数组中的所有详细信息。因为这将为您留下带有键的数组,所以请使用array_values()仅提取内容...

$a1 = array_column($array1,null,"flower_id");
$a2 = array_column($array2,null,"flower_id");
echo json_encode(array_values(array_intersect_key($a1, $a2)));

您的测试数据将给出...

[
    {
        "flower_id": "1",
        "flower_price": "1",
        "flower_name": "Nelumbo"
    },
    {
        "flower_id": "3",
        "flower_price": "2",
        "flower_name": "Ladys"
    },
    {
        "flower_id": "5",
        "flower_price": "2",
        "flower_name": "White"
    },
    {
        "flower_id": "9",
        "flower_price": "2",
        "flower_name": "Common"
    }
]