Prashanth Prashanth - 1 year ago 43
MySQL Question

How to merge two rows and get single array in Codeigniter/PHP?

I am working on Codeigniter for assigning multiple roles to the single user. For that I have created a table with following values.

Array
(
[Id] => 1
[Store_address_id] =>
[Customer_ref_id] => 193
[Role_ref_id] => 1
[Email_alert] => 0
[Sms_alert] => 0
[Admin_view] => 0
[Admin_save] => 0
[Admin_delete] => 0
[Master_view] => 1
[Master_save] => 1
[Master_delete] => 1
[Business_view] => 0
[Business_save] => 0
[Business_delete] => 0
[Analytics_view] => 1
[Analytics_delete] => 1
[Analytics_save] => 1
[Promotion_view] => 1
[Promotion_save] => 1
[Promotion_delete] => 1
)


But, in database I am having multiple rows for that I need to get the value with the validation like this

+----+----+----+
| i/p|i/p | o/p|
+----+----+----+
| 0 | 0 | 0 |
+----+----+----+
| 1 | 1 | 1 |
+----+----+----+
| 1 | 0 | 1 |
+----+----+----+
| 0 | 1 | 1 |
+----+----+----+


My table is like this

MySqlTable

I need to validate and fetch as a single array.

Answer Source

Following my comment thought I would suggest something like this to do it in your controller:

// set a permissions array and set to default values of 0
$permissions =  array(
    'Email_alert' => 0,
    'Sms_alert' => 0,
    'Admin_view' => 0,
    'Admin_save' => 0,
    'Admin_delete' => 0,
    'Master_view' => 0,
    'Master_save' => 0,
    'Master_delete' => 0,
    'Business_view' => 0,
    'Business_save' => 0,
    'Business_delete' => 0,
    'Analytics_view' => 0,
    'Analytics_delete' => 0,
    'Analytics_save' => 0,
    'Promotion_view' => 0,
    'Promotion_save' => 0,
    'Promotion_delete' => 0,
);

// get the rows
foreach ($results as $row) {
    // get each col name and value
    foreach ($row as $key => $value) {
        // make sure it is a value needed for the permissions array
        if(isset($permissions[$key])) {
            // this value is a permissions value, is it a 1
            if ($value == 1) {
                // set the permissions array to 1
                $permissions[$key] = 1;
            }
        }
    }
}

This is just me typing it out, so have not tested it and there may be some typo's. Hope it helps. There may be more efficient ways to do this but if you are only dealing with a few rows this would be fine.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download