简体   繁体   中英

Create dynamic associative array in php in foreach loop

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;

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);

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);

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);

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM