如何根据特定的列值检索数组?

时间:2019-04-22 12:56:49

标签: php json

我使用php从JSON API获取数组。如何根据选定的列值过滤此数组并返回过滤后的数组?

这是我的示例JSON数据:-

[{
  "attribute_group_name": "Location",
  "attribute_name": "Local",
  "item_id": "1111"
}, {
  "attribute_group_name": "Service",
  "attribute_name": "Cash On Delivery",
  "item_id": "0000"
}, {
  "attribute_group_name": "Service",
  "attribute_name": "Shipping",
  "item_id": "3333"
}, {
  "attribute_group_name": "Service",
  "attribute_name": "Insurance",
  "item_id": "4444"
}]

在abc.php中,我尝试使用array_filter,但它不起作用。

这是我在abc.php中的代码

<?php
    $url_Category_Main = "https://api.abc123.com/category/main";
    $data_Category_Main = json_decode(file_get_contents($url_Category_Main), true);

    function attribute_service($var)
    {
        return($data_Category_Main['attribute_group_name'] == 'Service');
    }

    $new = array_filter($data_Category_Main, "attribute_service");


    $count=0;
    foreach($new as $row_Category_Main):
?>


<div>
    <input class="styled-checkbox" style="display:inline-block;" id="styled-checkbox-1" type="checkbox" value="value1">
    <label><?= $row_Category_Main['attribute_name']; ?></label>
</div>

<?php endforeach; ?>

在这种情况下,如何获得一个由attribute_group_name = Service过滤并返回标签??中的值的数组?

预期结果:

货到付款

运输

保险

请帮助。谢谢。

1 个答案:

答案 0 :(得分:1)

要在函数内部使用的变量的名称是在参数上使用的名称,而不是实际数组的名称,该数组不在函数内部的范围内

function attribute_service($var)
{
    //return($data_Category_Main['attribute_group_name'] == 'Service');
    return($var['attribute_group_name'] == 'Service');
    //     ^^^^  the changed code
}

示例代码:

<?php
$j = '[{
  "attribute_group_name": "Location",
  "attribute_name": "Local",
  "item_id": "1111"
}, {
  "attribute_group_name": "Service",
  "attribute_name": "Cash On Delivery",
  "item_id": "0000"
}, {
  "attribute_group_name": "Service",
  "attribute_name": "Shipping",
  "item_id": "3333"
}, {
  "attribute_group_name": "Service",
  "attribute_name": "Insurance",
  "item_id": "4444"
}]';

function attribute_service($var)
{
    return($var['attribute_group_name'] == 'Service');
}

$data_Category_Main = json_decode($j, true);
$new = array_filter($data_Category_Main, "attribute_service");
//print_r($new);

foreach($new as $row):
?>
    <div>
        <input class="styled-checkbox" style="display:inline-block;" id="styled-checkbox-1" type="checkbox" value="value1">
        <label><?= $row['attribute_name']; ?></label>
    </div>
<?php    
endforeach;

结果

<div>
    <input class="styled-checkbox" style="display:inline-block;" id="styled-checkbox-1" type="checkbox" value="value1">
    <label>Cash On Delivery</label>
</div>
<div>
    <input class="styled-checkbox" style="display:inline-block;" id="styled-checkbox-1" type="checkbox" value="value1">
    <label>Shipping</label>
</div>
<div>
    <input class="styled-checkbox" style="display:inline-block;" id="styled-checkbox-1" type="checkbox" value="value1">
    <label>Insurance</label>
</div>