0

I want to loop through an array and get each element to pass as parameters to a constructor. here is my example

[user_by_province] => Array
    (
        [label] => Array
            (
                [0] => a
                [1] => b
                [2] => c
                [3] => d
                [4] => e
                [5] => f
            )

        [count] => Array
            (
                [0] => 2
                [1] => 1
                [2] => 1
                [3] => 1
                [4] => 7
                [5] => 1
            )

    )

Here is the constructor:

$pc = new C_PhpChartX(array(array('a','2'),
                            array('b','1'),
                            array('c','1'),
                            array('d','1'),
                            array('e','7'),
                            array('f','1')));

so how can i do that with php thanks for any help, may we can do that with array_map or no? thanks for any help

4 Answers 4

3

As you suggested array_map with multiple arguments could be a good solution.

<?php

$userByProvince = array(
    'label' => array('a', 'b', 'c', 'd', 'e', 'f'),
    'count' => array('1', '2', '3', '4', '5', '6'),
);

function combine($arg1, $arg2)
{
    return array($arg1, $arg2);
}

$arguments = array_map('combine', $userByProvince['label'], $userByProvince['count']);

$pc = new C_PhpChartX($arguments);

If you are using PHP 5.3 you can even substitute the function with a lambda expression to make the code more compact (see docs).

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

Comments

0

It's easier to use array_combine.

Comments

0

you can do something like this:

$my_array=array("user_by_province"=>array("label"=>array('a','b','c','d','e','f'),"count"=>array(2,1,1,1,7,1)));
   $new_array=array();
   for($i=0;$i< count($my_array['user_by_province']['label']);$i++){
       $new_values=array();
       array_push($new_values,$my_array['user_by_province']['label'][$i],$my_array['user_by_province']['count'][$i]);
       array_push($new_array,$new_values);
   }

Comments

0

supposed your given array is ordered and has the same amount of data, i.e. pairs:

loop over your data:

$input = array("user_by_province"
         => array("label" => array('a', 'b', 'c'),
                  "count" => array(1, 2, 3)));

$combined = array();

for($i = 0; $i < count($input['user_by_province']['label'] && $i < count($input['user_by_province']['count']; $i++)
{
    $combined[] = array($input['user_by_province']['label'][$i], $input['user_by_province']['count'][$i]);
}

$pc = new C_PhpChartX($combined);

Comments

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.