-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] には 1 つの値 (24 文字の文字列) しかないため、ループは 1 つしかありません。reason_and に各数値の値を持たせることは可能ですか?

これは可能ですか?私はかなり混乱しています。

参照用にこの質問を参照しましたが、まだ作業できる結果が得られません。前もって感謝します。

4

2 に答える 2

3

これ

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

する必要があります

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

これにより、文字列の連結ではなく、「配列のプッシュ」操作になります。次に'reason_and'配列になり、それに対してforeachします。

于 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 に答える