php数组函数。试图避免解包数组然后重新打包数组

时间:2013-04-10 18:05:42

标签: php arrays foreach

是否有一种更简单的方法可以将一个数组分解为一个额外的数组,而不是解压缩数组,运行explode函数然后重新打包数组,如下所示。这很好,我试图找出是否更容易。

    public function getStandardizationTerms()
    {

        $statement = $this->db->query('SELECT * FROM '.$this->std_table);
        $result = $statement->fetchAll(PDO::FETCH_ASSOC);

        $new_result = array();
        foreach($result as $term) {
            // the only purpose of this foreach loop is to turn the exception tables field into an array
            $new_result[] = array(              
                'key'          => $term['key'],
                'operator'     => $term['operator'],
                'fragment'     => $term['fragment'],
                'manufacturer' => $term['manufacturer'],
                'is_exception' => $term['is_exception'],
                'tables'       => explode(",",$term['tables'])
            );

        }       
        return $new_result;

    }   

2 个答案:

答案 0 :(得分:0)

你不能直接引用这个字段吗?

<?php
$myArray = Array ('field1' => "var1", 'field2' => "var2", 'field3' => "var3, var4, var5");
$myArray['field3'] = explode (",", $myArray['field3']);
print_r ($myArray);
?>

答案 1 :(得分:0)

如果您通过引用

循环遍历$terms,则无需创建新数组
foreach($result as &$term) {
    $term['tables'] = explode(",",$term['tables']);
}

另请参阅http://php.net/manual/en/control-structures.foreach.php

上的第二个示例