forep循环中的Php数组

时间:2013-05-24 15:06:46

标签: php arrays foreach

我一直在尝试从已经存在的数组创建一个多维数组。我这样做的原因是我可以将超级数组分成更加分类的版本,以便稍后我可以在另一个脚本中的那些类别上运行foreach。

这是一段代码//请阅读评论:)

$and = array();

if($this-> input-> post('and')) // This is the super array and[] from a previous input field
{
    if(preg_grep("/reason_/", $this-> input-> post('and'))) // Search for the reason_
    {
        foreach($this-> input-> post('and') as $value) // if reason_ is present 
        {
            $and['reason_and'] .= end(explode('_', $value)) . ' , '; // Remove everything before and including _ so then i would get only values like 1, 2, 3, 4, and then concatenate them to the index
        }
    }
    if(preg_grep("/status_/", $this-> input-> post('and'))) // Search for status
    {
        foreach($this-> input-> post('and') as $value) // If it is in the super array
        {
            $and['status_and'] .= end(explode('_', $value)) . ' , '; // Remove everything before and including _ so then I would get values again like 1,2,3,4,5 and then concatenate them to the index
        }
    }
}

这种方法并没有给我预期的结果,但是,我得到一个像这样的大字符串:

 array(2) { ["reason_and"]=> string(24) "2 , 3 , 4 , 3 , 4 , 5 , " 
            ["status_and"]=> string(24) "2 , 3 , 4 , 3 , 4 , 5 , " 

因此,据我所知(当时我对数组

进行了预测)
  

[reason_and]

我只得到一个循环,因为数组[“reason_and]只有一个值(24个字符串?)。是否可以让reason_and为每个数字都有一个值?

这甚至可能吗?我很困惑。

我已经提到这个question作为参考,但我仍然没有得到我可以使用的结果。提前谢谢。

2 个答案:

答案 0 :(得分:3)

        $and['reason_and'] .= end(explode('_', $value)) . ' , ';
                          ^^^^----

应该是

        $and['reason_and'][] = end(explode('_', $value)) . ' , ';
                          ^^--

将其转换为“数组推送”操作,而不是字符串连接。然后'reason_and'将成为一个数组,然后你就可以了解它。

答案 1 :(得分:1)

首先,preg_grep返回一个匹配值的数组,所以

    $andArray = $this-> input-> post('and'); // This is the super array and[] from a previous input field

    if($andArray) {

    $reason = preg_grep("/reason_/", $andArray); // Search for the reason_

       if($reason) { // if reason_ is present 

foreach($reason as $value) {
                $and['reason_and'] .= end(explode('_', $value)) . ' , '; // Remove everything before and including _ so then i would get only values like 1, 2, 3, 4, and then concatenate them to the index
            }
        }

    $status = preg_grep("/status_/", $andArray); // Search for status

        if($status) {

            foreach($status as $value){ // If it is in the super array

                $and['status_and'] .= end(explode('_', $value)) . ' , '; // Remove everything before and including _ so then I would get values again like 1,2,3,4,5 and then concatenate them to the index
            }
        }
    }

或者如果您需要将结果作为数组,则删除','并用[];

替换点