数组-从数组中选择子孩子的ID

时间:2018-10-01 22:29:04

标签: php arrays

我从一个将允许的或有效的url段及其ID排序到另一个数组的函数构建了这个数组。我可以通过将url slug传递给类别来调用当前类别ID。现在,我需要获取子类别ID(如果有的话),以便可以从数据库中调用适当的项以进行显示。

这里有一个数组示例:

Array (
    [radios] => 1
    [radios/motorola] => 2
    [radios/motorola/handheld] => 3
    [radios/motorola/mobile] => 4
    [radios/icom] => 5
    [radios/icom/handheld] => 6
    [radios/icom/mobile] => 7
    [radios/mics-and-speakers] => 8
    [radios/mounts] => 9
    [radios/radio-other] => 10
    [misc] => 11
    [misc/led] => 12
    [phones] => 13
    [phones/samsung] => 14
    [phones/lg] => 15
    [phones/motorola] => 16
    [phones/huawei] => 17
    [phones/blackberry] => 18
    [phones/flip] => 19
    [boosters] => 20
    [boosters/standalone] => 21
    [boosters/indoor-antenna] => 22
    [boosters/outdoor-antenna] => 23
    [boosters/connections] => 24
    [accessories] => 25
    [accessories/cases] => 26
    [accessories/other] => 27
    [internet] => 28
    [internet/fusion] => 29
    [internet/point-to-point] => 30
    [internet/hotspots] => 31
    [internet/gateways] => 32
    [internet/switches] => 33
    [cameras] => 34
    [cameras/complete-kits] => 35
    [cameras/additional-cameras] => 36
    [cameras/other] => 37
);

如您所见,每个结果都指向该组的类别ID。如果我访问以下网址:

http://example.com/store/cameras

我可以打印出正确的THE PATH CURRENTLY IS: 34。由于它下面有孩子,因此我还需要他们的ID以及他们任何孩子的ID等,以此类推。这样,在radios上,我可以显示所有子类别项目,并在radios/motorola上显示我只展示基于摩托罗拉的商品及其子代,等等。

如果有一种简便的方法,可以使用我现在拥有的这个数组对所有子级(如果有)进行排序,然后仅返回其ID(最好是在新的数组中)以显示数据库项?

2 个答案:

答案 0 :(得分:1)

You might want to create a function like this to filter your array,

function filterArray($array, $term) {   
    $pattern = "/\b" . str_replace($term, '/', '\/') . "\b/i";
    foreach($array as $key => $value) {
        if(preg_match($pattern, $key)) {
            /* Following condition makes sure that your search
            will match starting from the beginning. */          
            if (stripos(trim($key), $term) === 0){
                $filtred[] = $value;
            }
        }
    }
 }

Then call the above function with the $array and your search $term.

filterArray($array, 'radios') will give you this,

Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 [8] => 9 [9] => 10 )

filterArray($array, 'radios/motorola') will give you this,

Array ( [0] => 2 [1] => 3 [2] => 4 )

And so on.. I hope this helps.

答案 1 :(得分:-1)

您可以尝试双层数组,以便可以存储这样的值,

Array (
[name] => John
[surname] => Smith
[contact] => Array ( 
                    [address] => 18 Maple Street
                    [number] => 555 477 77 77
                    )
)

这样,如果您需要从“联系人”中打印某些内容,则可以使用循环并打印联系人字段的所有子项。