1

基本的に、いくつかの配列が互いにネストされた比較的複雑なコードがあります。私がやりたいことは厳密には不可能だと思います:

$selector = true,
 $main_array = array(
  'general' = array(
   'another_array' = array(
    'option1' = array(
     'title' = 'Some Title',
     'type' = 'select',
       if ($selector == true) {
    'option2' = array(
     'title' = 'Some title',
     'type' = 'select',
     } else
    ...

上記が不可能であることは承知しています。三項演算子を使用できることは知っていますが、試してみるとうまくいきませんでした。この問題を解決するためのより良い方法があることは知っていますが、私が知る限り、すべての方法で構造全体を変更する必要があり (相互にネストされた多くの配列があるため)、やりたくないので、私の問題は、全体を変更せずにこの条件付きの作業を行うために使用できる方法はありますか?

どうもありがとう

4

4 に答える 4

3

I'm assuming that you are not actually attempting to assign arrays to string literals, so judiciously adding some '>'s

And yes, if I understand what you are looking for, it can be accomplished with a ternary operation, as follows:

$main_array = array(
 'general' => array(
  'another_array' => array(
   'option1' => array(
    'title' => 'Some Title',
    'type' => 'select',
   'option2' => (($selector == true) ?
    array(
     'title' => 'Some title',
     'type' => 'select',
    ) : 'It was false'
 )))));
于 2012-11-21T23:57:39.150 に答える
0

Use the ternary operator. With the ternary operator, this:

if($selector == true){
    $foo = 'something'; 
} else {
    $foo = 'something else';
}

can become this:

$foo = ($selector == true) ? 'something' : 'something else';

Your example code would look something like this:

$selector = true;    
$main_array = array(
    'general' => array(
         'another_array' => array(
              'option1' => array(
                    'title' => 'Some Title',
                    'type' => 'select',
                    'option2' => ($selector == true) ? array('title' = 'Some title','type' = 'select') : array('title' => 'Some other title', 'type' => 'Some other type')
                ...
于 2012-11-21T23:57:14.793 に答える
0

もしあなたが 3 項式ではなく if/else を使いたいと思っているなら、結果のいくつかを少し早く出すことができます。

       if ($selector == true) {
    $preset2 = 配列(
     'title' = '何らかのタイトル',
     'タイプ' = '選択'
     );
    }
    そうしないと
    {
     $preset2 = 配列( ... );
    }

 $main_array = 配列(
  '一般' = 配列(
   'another_array' = 配列(
    'option1' = 配列(
     'title' = '何らかのタイトル',
     'タイプ' = '選択' ),
    'option2' = $preset2,
于 2012-11-22T00:47:47.583 に答える
0

その通りです。やりたいことは、やりたいようには実現できません。コードを再構築する必要があります。if何がプッシュされるかを決定するために必要なステートメントを使用して、各要素を個別に配列にプッシュできます。

于 2012-11-21T23:42:52.763 に答える