Vlammuh
Vlammuh

Reputation: 157

Split array keys by integer

I have an array like this:

array(10) { 
    [1]=> string(10) "Question 1"
    ["1a"]=> string(7) "option1"
    ["1b"]=> string(7) "option2"
    ["1c"]=> string(7) "option3"
    ["1d"]=> string(7) "option4"
    [2]=> string(10) "Question 2"
    ["2a"]=> string(7) "option1"
    ["2b"]=> string(7) "option2"
    ["2c"]=> string(7) "option3"
    ["2d"]=> string(7) "option4"
}

I want to split the array and echo the values between <li> tags. The problem is that, when I try to loop through the array keys, I cannot figure out how to sort them per integer in the array key and it echoes all elements between separate <li> tags instead of one for the five values of the keys containing 1, one for the five values of the keys containing 2, and so on.

This is the php code I'm currently using:

$form = array();

    foreach($_POST as $key => $val) {

    $q_answers = array();

    if (is_numeric($key)) {

        $question = trim(htmlspecialchars($val));

    } else if (is_string($key) && !empty($val)) {

        $q_answers[] = '<input type="button" value="'.trim(htmlspecialchars($val)).'" data-skip="0" />';

    }
    $form[] = $question.' '.implode(' ', $q_answers);

}

    $result = '
<ul>
    <li>'.implode('</li>
    <li>', $form).'</li>
</ul>';

}

Here's an example of what I am looking for:

Array:

Array(10) {
    [1]=> "Question 1"
    [1a]=> "option1"
    [1b]=> "option2"
    [1c]=> "option3"
    [1d]=> "option4"
    [2]=> "Question 2"
    [2a]=> "option1"
    [2b]=> "option2"
    [2c]=> "option3"
    [2d]=> "option4"
}

Output:

<ul>
    <li>Question 1: option1 option2 option3 option4</li>
    <li>Question 2: option1 option2 option3 option4</li>
</ul>

Upvotes: 0

Views: 76

Answers (1)

Jordi vd M
Jordi vd M

Reputation: 88

You could try this:

$array = {};
$options1 = {}
$options2 = {}
$options1[1a] = "option1";
$options1[1b] = "option2";
$options1["Name"] = "Question 1";
$options2[2a] = "option1";
$options2[2b] = "option2";
$options2["Name"] = "Question 2";
$array[1] = $options1;
$array[2] = $options2;
echo("<ul>");
foreach ($array as $option){
echo("<li>" . $option["Name"] . ":");
foreach ($optionas $suboption){
echo(" " . $suboption);
}
echo("</li>");
}
echo("</ul>");

You could use functions to fast-build these arrays :)

Upvotes: 0

Related Questions