在PHP显示阵列块 [英] Displaying array chunks in php

查看:75
本文介绍了在PHP显示阵列块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试显示其中元素位于数组的特定块。

举例来说,可以说这是我的数组

 阵列

    [0] =>排列
        (
            [1] =>一个
            [2] => b
            [3] => C
            [4] => ð
            [5] => Ë
        )    [1] =>排列
        (
            [6] => F
            [7] => G
            [8] => H
            [9] =>一世
            [10] => Ĵ
        )

我如何搜索的数组,例如第10项,并仅选择大块其位于?

修改

感谢您的答案,但是我没有需要一个函数,所以我这个问题,简单的解决方案上来了,我想:

  $ =的temp1 array_chunk($ cart_items,5,真正的);
的foreach($ temp1中为$关键=> $值){
    的foreach($值$键2 => $值2){
        如果($键2 == $的itemid){
            $ C_ID = $关键;
        }
        其他{        }
    }
}


解决方案

警告:我是很新的PHP(一开始周弄点回来)

这个怎么样:

 函数findChunks($数组$键){
    返回array_filter($阵列功能($子数组)使用($键){
        返回array_key_exists($键,$子阵);
    });
}$块= findChunks($ A,10);
后续代码var_dump($块);

请注意:这将返回多个块的如果的有与他们相同的密钥(这是完全有可能的,这取决于你的数据结构)多个块

如果你肯定只希望它匹配的第一个块, array_filter()可能是做太多的工作,因为它会遍历整个外部阵列是否需要它或不。这可能是重要到你的数组有多大。

如果性能比的意图清晰更重要的,然后使用一个更传统的条件循环可能会更罚单。

im trying to display a specific chunk of an array where an element is located.

for example, lets say this is my array

Array
(
    [0] => Array
        (
            [1] => a
            [2] => b
            [3] => c
            [4] => d
            [5] => e            
        )

    [1] => Array
        (
            [6] => f
            [7] => g
            [8] => h
            [9] => i
            [10] => j   
        )
)

how do i search the array for the 10th key for example, and choose only the chunk its located in?

EDIT

thanks for the answers, however i didnt need a function so i came up with this, simple solution, i think:

$temp1 = array_chunk($cart_items, 5,true);
foreach ($temp1 as $key => $value) {
    foreach ($value as $key2 => $value2) {
        if($key2 == $itemid){
            $c_id = $key;
        }
        else{

        }
    }
}

解决方案

Caveat: I am very new to PHP (started a coupla weeks back).

How about this:

function findChunks($array, $key){
    return array_filter($array, function($subArray) use ($key){
        return array_key_exists($key, $subArray);
    });
}

$chunks = findChunks($a, 10);
var_dump($chunks);

Note: this will return multiple chunks if there are multiple chunks with the same key in them (which is entirely possible, depending on your data structure).

If you definitely only wanted the first chunk which matched, array_filter() is possibly doing too much work, as it will traverse the entire outer array whether you need it to or not. That that might matter is down to how big your arrays are.

If performance was more important than clarity of intent, then using a more traditional conditional loop might be more the ticket.

这篇关于在PHP显示阵列块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆