1

I have loop like this

foreach($this->input->post('users') as $value)
        {
            foreach($this->input->post('group_name') as $v)
            {
                echo $value.','.$v.'<br>';

            }
        }

And its ouput is

17,5
17,6
18,5
18,6
19,5
19,6
20,5
20,6

Now i want to create an associative array like this using the above values.

array(
        array(
                'user_id' => 17,
                'group_id' => 15
        ),
       ....
       ....
      array(
                'user_id' => 20,
                'group_id' => 6
        )

)

How can i do that I've tried this in foreach loop but it will print two separate arrays.

            $temp['user_id'][]=$v;
            $temp['group_id'][]=$value;
0

4 Answers 4

6

All you have to do is append array with respective values.

$result = [];
foreach($this->input->post('users') as $value)
{
        foreach($this->input->post('group_name') as $v)
        {
                $result[] = ['user_id' => $value, 'group_id' => $v];
        }
}
var_dump($result);
Sign up to request clarification or add additional context in comments.

7 Comments

But i don't want the keys
Arrays stores values on keys, see docs : php.net/manual/en/language.types.array.php
Please look at the sample output array in my question
Yes I did, they also have keys (numeric keys)
No there is no keys
|
1

This loop should help you out.

$resultArray = [];
foreach($this->input->post('users') as $value) {
    foreach($this->input->post('group_name') as $v) {
        $resultArray[] = array(
            'user_id' => $value,
            'group_id' => $v,
        );
    }
}

var_dump($resultArray);

Comments

0

It's very simple, you just have to append/push the child array into main array.

Like this,

$main_array=array();
foreach($this->input->post('users') as $value)
        {
            foreach($this->input->post('group_name') as $v)
            {
                $group_array=array();
                $group_array["group_id"]=$v;
                $group_array["user_id"]=$value;
                $main_array[]=$group_array;
                //echo $value.','.$v.'<br>';
            }
        }
print_r($group_array);

You may also use array_push() to push child array into main array.

Syntax for that would be,

array_push($main_array, $child_array);

Comments

0

Can u try this

$temp = array();
foreach($this->input->post('users') as $key=>$value)
    {
        foreach($this->input->post('group_name') as $v)
        {
            $temp[$key]['user_id']=$v;

            $temp[$key]['group_id']=$value;

        }
    }

print_r($temp);

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.