Search code examples
phparrayswordpresspermissionsarray-merge

How to add permission array to an existing array


I am building a web app that will have the option to assign an array item to be visible by a group (or groups). This all would be passed through to Wordpress to update_option but for the basics it is a PHP question.

To me it would be a checkbox that would be a true or false for that group and if they have permission:

     | Title 1   //$array['label']
-------------------------
Opt1 |    x   
-------------------------
Opt2 |    x   
-------------------------
Opt3 |        
-------------------------
Opt4 |    
-------------------------
Opt5 |    x

Where the $array would have the values pulled from here:

$array = array(
    array( 'label' => 'Title 1',    'class' => 'loc01' ),
    array( 'label' => 'Title 2',    'class' => 'loc02' ),
    array( 'label' => 'Title 3',    'class' => 'loc03' ),
    array( 'label' => 'Title 4',    'class' => 'loc04' ),
    array( 'label' => 'Title 5',    'class' => 'loc05' ),
);

The $array is created by array_merge() with the original, and whatever new array is created by the user on the front end.

$old_array  = $array;
$new_array  = array( array( 'x' => $array_label, 'y' => $array_class ) );
$new_array  = array_merge( $old_array, $new_array );

What would be the best way to add the permission to the $array?

Should it be this:

$array = array(
    array( 'label' => 'Title 1',    'class' => 'loc01', 'permission' => array( 'Opt1', 'Opt2', 'Opt3' ) ),
    ...
    array( 'label' => 'Title 5',    'class' => 'loc05' ),
);

And how would I best be able to verify permission on the front end when looping the output?

foreach( $array as $item )
    if( in_array( 'current_group', $item[permission] )
        ...

Hope this makes sense!


Solution

  • The best way for you to do this is below:

    foreach($array as $key => $val)
    {
      $array[$key]['permission'] = 'true or false(your choice)';
    }