-1

我一直在尝试从已经存在的数组创建一个多维数组。我这样做的原因是我可以将超级数组分成更分类的版本,以便稍后我可以在另一个脚本中仅对这些类别运行 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 , " 

因此,据我所知(这是有限的),当我尝试对数组进行 foreach 时

[reason_and]

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

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

我已经提到了这个问题以供参考,但我仍然没有得到我可以使用的结果。提前致谢。

4

2 回答 2

3

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

应该

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

这将其变成了“数组推送”操作,而不是字符串连接。然后'reason_and'将是一个数组,您可以遍历它。

于 2013-05-24T15:17:06.550 回答
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
            }
        }
    }

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

于 2013-05-24T15:34:42.253 回答