-2

Working on a poll script, but I have little problems with the options of a poll, creating a new array of it.

The actual example array contains 3 sub-arrays with options, sum of votes and percentage:

Array
        (
            [poll_options] => Array
                (
                    [0] => Good
                    [1] => Bad
                    [2] => I do not care
                )

            [poll_answers] => Array
                (
                    [0] => 3
                    [1] => 1
                    [2] => 1
                )

            [poll_percentage] => Array
                (
                    [0] => 60
                    [1] => 20
                    [2] => 20
                )

        )

Now I need to create a new array of the values, the result must be like this:

Array
        (
            [0] => Array
                (
                    [option] => Good
                    [answers] => 3
                    [percentage] => 60
                )

            [1] => Array
                (
                    [option] => Bad
                    [answers] => 1
                    [percentage] => 20
                )

            [2] => Array
                (
                    [option] => I do not care
                    [answers] => 1
                    [percentage] => 20
                )

        )

Whatever tried so far, I just can't reach this result I want. Any ideas?

lickmycode
  • 2,069
  • 2
  • 19
  • 20
  • what u try , post the code ! 10x – Haim Evgi Dec 26 '13 at 15:50
  • @HaimEvgi: posting everything I tried today already and I would hit the maximum allowed characters of a question. I think for this question it is not needed to post more code as I did. – lickmycode Dec 26 '13 at 15:54

3 Answers3

3
$new_array = array();
foreach (array_keys($old_array['poll_options']) as $i) {
    $new_array[] = array(
        'option' => $old_array['poll_options'][$i],
        'answers' => $old_array['poll_answers'][$i],
        'percentage' => $old_array['poll_percentage'][$i]
    );
}

DEMO

Barmar
  • 741,623
  • 53
  • 500
  • 612
1
$newArray=Array();
$count=count($array["poll_oprions"]);
for ($i = 0; $i < $count; $i++) {
    $newElem=Array(); 
    $newElem["option"]=$array["poll_option"][$i];
    $newElem["answers"]=$array["poll_answers"][$i];
    $newElem["percentage"]=$array["poll_percentage"][$i];
    $newArray[]=$newElem;
}
Ahmed Siouani
  • 13,701
  • 12
  • 61
  • 72
0

Use array_column():

$new_array = array();
$new_array[] = array(
    'option' => array_column($old_array, 0),
    'answers' => array_column($old_array, 1),
    'percentage' => array_column($old_array, 2),
);

Demo.

Note that this function is => PHP 5.5.0. If you're using an older version of PHP, you can use the implementation written in plain PHP (by the author of this function). It's available on GitHub.

Amal Murali
  • 75,622
  • 18
  • 128
  • 150