0

我需要访问多个数组,问题在于当我到达下面需要的数组时,我不能传统地访问它,因为密钥每次都会不同。

我正在处理以下数组:

Array
(
    [oe_schedule_charge] => Array
        (
            [617cdb2797153d6fbb03536d429a525b] => Array
                (
                    [schedule] => 
                    [args] => Array
                        (
                            [0] => Array
                                (
                                    [id] => cus_2OPctP95LW8smv
                                    [amount] => 12
                                )

                        )

                )

        )

)

将会有数百个这样的数组,我需要一种方法来有效地访问其中的数据。我正在使用以下代码和预期的输出:

function printValuesByKey($array, $key) {
    if (!is_array($array)) return;
    if (isset($array[$key])) 
        echo $key .': '. $array[$key] .'<br>';
    else
        foreach ($array as $v)
            printValuesByKey($v, $key);
}

$cron = _get_cron_array();

foreach( $cron as $time => $hook ) {
    if (array_key_exists('oe_schedule_charge', $hook)) {
        echo '<div>';
        echo date('D F d Y', $time);
        echo printValuesByKey($hook, 'amount');
        echo printValuesByKey($hook, 'id');
        echo '</div>';
    }
}

但我从来没有处理过这么多数据,所以我想采取适当的预防措施。任何可以以有效方式访问这样的多维数组的信息将不胜感激。

4

1 回答 1

1

我会考虑将它加载到一个对象中,然后编写成员函数来获得你想要的。

class myclass { 

private $_uniqueKey;
private $_schedule;
private $_args = array();

private $_amount = array();
private $_id = array();

public function __construct($arrayThing)
{
    foreach($arrayThing['oe_schedule_charge'] as $uniqueKey => $dataArray)
    {
        $this->_uniqueKey = $uniqueKey;
        $this->_schedule = $dataArray['schedule'];
        $this->_args = $dataArray['args'];
    }
    $this->_afterConstruct();
}

private function _afterConstruct()
{
    foreach($this->_args as $argItem)
    {
        if(isset($argItem['amount']) && isset($argItem['id']))
        {
            $this->_amount[] = $argItem['amount'];
            $this->_id[] = $argItem['id'];
        }
    }
}

public function getUniqueKey()
{
    return $this->_uniqueKey;
}

public function getSchedule()
{
    return $this->_schedule;
}

public function getArgs()
{
    return $this->_args;
}

public function printShitOut($time)
{
    //You define this. But if you do a print_r( on the object, it will tell you all the items you need. )

}

//code would be like this:

$cron = _get_cron_array();

foreach( $cron as $time => $hook ) 
{
    $obj = new myclass($hook);
    $obj->printShitOut($time);
}
于 2013-08-16T05:09:48.380 回答