1

I don't manage to get this piece of code working. I need to get an array depending of the variable posted. I guess it's obvious but I can't find the slution.

$choice1 =
    array (
        'order' => array (1,2,3,4,5),
            'settings' => (1,0,1)
    );
$choice2 =
    array (
        'order' => array (1,5,3,2,4),
            'settings' => (0,0,0)
    );
if(isset($_POST['choice'])) {
    $template_to_get = $_POST['choice'];
    $order_display = $template_to_get['order'];          // Here is the problem
    echo json_encode(array('order' => $order_display));
}

Also tried:

$order_display = $$template_to_get['order'];
$order_display = "$".$template_to_get['order'];
...

If I write this line it works but I don't know if it's choice1 or choice 2 which will be posted:

$order_display = $choice1['order'];

I would like to get the (1,2,3,4,5) array as output. (I simplified but I have around 20 choiceX)

Thanks!

4 Answers 4

2

I would group your choices up into a single num indexed array and not add the smell of variable variables:

$choices = array(
    1 => array(
        'order' => array (1,5,3,2,4),
        'settings' => (0,0,0),
    ),
    2 => array(
        'order' => array (1,2,3,4,5),
        'settings' => (1,0,1)
    ),
);

if(isset($_POST['choice'])) {
    $template_choice = $_POST['choice'];
    echo json_encode(array('order' => $choices[ $template_choice ]['order'] ));
}

Or something very close.

Edit: Note that the same would work perfectly fine if you're posting strings in $_POST['choice'], for example 'template_1' could be posted and matched in:

$choices = array(
    'template_1' => array( ... );
    ...
);

Cheers

Sign up to request clarification or add additional context in comments.

Comments

1

It's a little hard to work out what you want here, but I think it's this:

$order_display = $choice1[$_POST['choice']];

1 Comment

It's not what I want to do, I have edited my question to make it more clear
0
foreach ($choice as $key => $val)
foreach ($val as $nval)
  echo $key . ' : ' . $nval . '<br />';

Comments

0
$varname = 'choice' . $_POST['choice'];
$order_display = $$varname['order'];

1 Comment

I get: Notice: Undefined variable: c in... at the 3rd line. "c" is the first character of what I post

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.