0

Sorry my english is bad, and i want to asking here for duplicate questions with so many answer maybe not in my case, i have an array produced from multiple array $_POST like

<input type="checkbox" class="styled" data-controller="company-group" data-action="index" name="checkbox[company-group][index]" value="1" checked=""> 
<input type="checkbox" class="styled" data-controller="company-group" data-action="create" name="checkbox[company-group][create]" value="1" checked=""> 
<input type="checkbox" class="styled" data-controller="company-group" data-action="update" name="checkbox[company-group][update]" value="1" checked=""> 
<input type="checkbox" class="styled" data-controller="company-group" data-action="delete" name="checkbox[company-group][delete]" value="1" checked=""> 

<input type="checkbox" class="styled" data-controller="company-industry" data-action="index" name="checkbox[company-industry][index]" value="1" checked=""> 
<input type="checkbox" class="styled" data-controller="company-industry" data-action="create" name="checkbox[company-industry][create]" value="1" checked=""> 
<input type="checkbox" class="styled" data-controller="company-industry" data-action="update" name="checkbox[company-industry][update]" value="1" checked=""> 
<input type="checkbox" class="styled" data-controller="company-industry" data-action="delete" name="checkbox[company-industry][delete]" value="1" checked=""> 

$_POST['checkbox']

checkbox: checkbox%5Bcompany-group%5D%5Bindex%5D=1&checkbox%5Bcompany-group%5D%5Bview%5D=1&checkbox%5Bcompany-group%5D%5Bcreate%5D=1&checkbox%5Bcompany-group%5D%5Bupdate%5D=1&checkbox%5Bcompany-group%5D%5Bdelete%5D=1&checkbox%5Bcompany-industry%5D%5Bindex%5D=1&checkbox%5Bcompany-industry%5D%5Bview%5D=1&checkbox%5Bcompany-industry%5D%5Bcreate%5D=1&checkbox%5Bcompany-industry%5D%5Bupdate%5D=1&checkbox%5Bcompany-industry%5D%5Bdelete%5D=1

and i have handle with this code :

$asi = urldecode($_POST['checkbox']);
$asu = explode('&', $asi);
$arr = array();
$arr2 = array();

foreach ($asu as $key) 
{
    list ($ass, $iss) = explode('=', $key);
    preg_match_all('/\[(.*?)\]/', $ass, $sue);
    $arr2[] = array_merge_recursive($sue[1]);
}

and this my $arr2 result :

print_r()

Array
(
    [0] => Array
        (
            [0] => company-group
            [1] => index
        )

    [1] => Array
        (
            [0] => company-group
            [1] => view
        )

    [2] => Array
        (
            [0] => company-group
            [1] => create
        )

    [3] => Array
        (
            [0] => company-group
            [1] => update
        )

    [4] => Array
        (
            [0] => company-group
            [1] => delete
        )

    [5] => Array
        (
            [0] => company-industry
            [1] => index
        )

    [6] => Array
        (
            [0] => company-industry
            [1] => view
        )

    [7] => Array
        (
            [0] => company-industry
            [1] => create
        )

    [8] => Array
        (
            [0] => company-industry
            [1] => update
        )

    [9] => Array
        (
            [0] => company-industry
            [1] => delete
        )
)

var_export()

array (
  0 => 
  array (
    0 => 'company-group',
    1 => 'index',
  ),
  1 => 
  array (
    0 => 'company-group',
    1 => 'view',
  ),
  2 => 
  array (
    0 => 'company-group',
    1 => 'create',
  ),
  3 => 
  array (
    0 => 'company-group',
    1 => 'update',
  ),
  4 => 
  array (
    0 => 'company-group',
    1 => 'delete',
  ),
  5 => 
  array (
    0 => 'company-industry',
    1 => 'index',
  ),
  6 => 
  array (
    0 => 'company-industry',
    1 => 'view',
  ),
  7 => 
  array (
    0 => 'company-industry',
    1 => 'create',
  ),
  8 => 
  array (
    0 => 'company-industry',
    1 => 'update',
  ),
  9 => 
  array (
    0 => 'company-industry',
    1 => 'delete',
  ),
)

json_encode()

[["company-group","index"],["company-group","view"],["company-group","create"],["company-group","update"],["company-group","delete"],["company-industry","index"],["company-industry","view"],["company-industry","create"],["company-industry","update"],["company-industry","delete"]

How to merge value on same key while looping, My desire result is :

Array
(
    [0] => Array
        (
            [key] => company-group
            [val] => Array (
                        [0] => index,
                        [1] => create,
                        [2] => update,
                        [3] => delete,
            )
        )

    [1] => Array
        (
            [key] => company-industry
            [val] => Array (
                        [0] => index,
                        [1] => create,
                        [2] => update,
                        [3] => delete,
            )
        )
)

Thanks for advice !

adyoi
  • 87
  • 1
  • 14
  • Would you possibly be more interested in this easier/simpler process/result? https://3v4l.org/qrA2L or https://3v4l.org/tiIqL If so, please edit your question and I'll post this as an answer. – mickmackusa Oct 04 '18 at 10:50
  • Why isn't 'view' part of the expected result? Is it just a typo? – Andreas Oct 04 '18 at 10:55
  • Read the manual more carefully: _Using this function **without the result parameter** is highly DISCOURAGED and DEPRECATED as of PHP 7.2._ ...Look, you are literally asking for advice (your last sentence in the question), I am trying to show you a better way. In what way is your script benefiting from a 3-level-deep output array. – mickmackusa Oct 04 '18 at 10:57
  • What are you doing next with this data? – mickmackusa Oct 04 '18 at 11:10
  • Okay, cool. I can't see any benefit to a 3-level array. How are you querying this data into your database? 2 rows to be inserted? 1 row? 8 rows? What is the structure like? – mickmackusa Oct 04 '18 at 11:14
  • @ady I'm still wondering about these unanswered queries that I made about your question. I'd like to help you and future researchers realize a professional resolution. I know this is old, but if you don't mind, let's move this page toward a resolution. – mickmackusa Jun 17 '20 at 22:55

4 Answers4

2

If you are going to lump all this checkbox data into a table column as json, then I'll recommend a more condensed array structure before json encoding the data.

parse_str() will convert you querystring-formatted data into a desirable associative array of associative arrays (each value being 1).

From there, overwrite the subarrays to move the keys to values, then generate your json array.

Now your data can be simply INSERTed into your database as a compact, portable string.

Code: (Demo)

$_POST['checkbox'] = 'checkbox%5Bcompany-group%5D%5Bindex%5D=1&checkbox%5Bcompany-group%5D%5Bview%5D=1&checkbox%5Bcompany-group%5D%5Bcreate%5D=1&checkbox%5Bcompany-group%5D%5Bupdate%5D=1&checkbox%5Bcompany-group%5D%5Bdelete%5D=1&checkbox%5Bcompany-industry%5D%5Bindex%5D=1&checkbox%5Bcompany-industry%5D%5Bview%5D=1&checkbox%5Bcompany-industry%5D%5Bcreate%5D=1&checkbox%5Bcompany-industry%5D%5Bupdate%5D=1&checkbox%5Bcompany-industry%5D%5Bdelete%5D=1';
parse_str($_POST['checkbox'], $output);

var_export($output['checkbox']);
echo "\n---\n";
echo json_encode(array_map('array_keys', $output['checkbox']));

Output:

array (
  'company-group' => 
  array (
    'index' => '1',
    'view' => '1',
    'create' => '1',
    'update' => '1',
    'delete' => '1',
  ),
  'company-industry' => 
  array (
    'index' => '1',
    'view' => '1',
    'create' => '1',
    'update' => '1',
    'delete' => '1',
  ),
)
---
{"company-group":["index","view","create","update","delete"],"company-industry":["index","view","create","update","delete"]}
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
  • @adyoi With my solution you can avoid all that `urldecode()`, `explode()`, `foreach () {list () = explode(); preg_match_all(); array_merge_recursive();}` convolution. You really shouldn't be using any of that stuff when there is a much more direct alternative. ...why, oh why, do I care so much? – mickmackusa Oct 04 '18 at 12:12
0

To only answer your question, how to transform arr2.
You can loop the array and build a new array.
There is most likely a better way with using the post array but my lunch break is over, so I'll leave that to Mickmack.

Foreach($arr2 as $sub){
    $new[$sub[0]]["key"] = $sub[0];
    $new[$sub[0]]["val"][] = $sub[1];
}

Var_dump(array_values($new));

https://3v4l.org/HKM7S

Andreas
  • 23,610
  • 6
  • 30
  • 62
0

Instead of using key as a key you could use actual array keys.

foreach ($asu as $key) 
{
    list ($ass, $iss) = explode('=', $key);
    preg_match_all('/\[(.*?)\]/', $ass, $sue);
    $arr2[$key][] = $sue[1];
}
Code Spirit
  • 3,992
  • 4
  • 23
  • 34
0

Short Answer:

$result=[];
foreach ($_POST["checkbox"] as $i=>$checkbox){
    $result[]=["key"=>$i,"val"=>array_keys($checkbox)];
}

echo "<pre>";
var_export($result);
echo "</pre>";


?>

if use jquery read this link to send object, if use text query string convert it : parse_str($_POST["checkbox"], $array);

php default behavior is:

<?php
echo "<pre>";
var_dump($_POST);
echo "</pre>";
?>
<form action="test.php" method="post">
    <input type="checkbox" class="styled" data-controller="company-group" data-action="index" name="checkbox[company-group][index]" value="1" checked="">
    <input type="checkbox" class="styled" data-controller="company-group" data-action="create" name="checkbox[company-group][create]" value="1" checked="">
    <input type="checkbox" class="styled" data-controller="company-group" data-action="update" name="checkbox[company-group][update]" value="1" checked="">
    <input type="checkbox" class="styled" data-controller="company-group" data-action="delete" name="checkbox[company-group][delete]" value="1" checked="">
    <br>
    <input type="checkbox" class="styled" data-controller="company-industry" data-action="index" name="checkbox[company-industry][index]" value="1" checked="">
    <input type="checkbox" class="styled" data-controller="company-industry" data-action="create" name="checkbox[company-industry][create]" value="1" checked="">
    <input type="checkbox" class="styled" data-controller="company-industry" data-action="update" name="checkbox[company-industry][update]" value="1" checked="">
    <input type="checkbox" class="styled" data-controller="company-industry" data-action="delete" name="checkbox[company-industry][delete]" value="1" checked="">
    <input type="submit">

result:

array(1) {
  ["checkbox"]=>
  array(2) {
    ["company-a"]=>
    array(2) {
      ["index"]=>
      string(1) "1"
      ["delete"]=>
      string(1) "1"
    }
    ["company-b"]=>
    array(3) {
      ["create"]=>
      string(1) "1"
      ["update"]=>
      string(1) "1"
      ["delete"]=>
      string(1) "1"
    }
  }
}

for your desire:

<?php

$result=[];
foreach ($_POST["checkbox"] as $i=>$checkbox){
    $temp=["key"=>$i];

    foreach ($checkbox as $val_key=>$val){
        $temp["val"][]=$val_key;
    }

    $result[]=$temp;
}

echo "<pre>";
var_export($result);
echo "</pre>";

method2:

$result=[];
foreach ($_POST["checkbox"] as $i=>$checkbox){
    $result[]=["key"=>$i,"val"=>array_keys($checkbox)];
}

echo "<pre>";
var_export($result);
echo "</pre>";


?>
PersianMan
  • 924
  • 1
  • 12
  • 29
  • Yes, this is sensible, but the OP is passing with serialize via ajax. (this detail was commented earlier but has been deleted) – mickmackusa Oct 04 '18 at 11:02
  • https://stackoverflow.com/questions/1184624/convert-form-data-to-javascript-object-with-jquery – PersianMan Oct 04 '18 at 11:06
  • @adyoi sure object is fastest!!! it is default action ; but if you like string processing use ```parse_str($_POST["checkbox"], $array);``` to convert – PersianMan Oct 04 '18 at 11:45
  • @adyoi , instead of multiple foreach ...> use ```parse_str($_POST["checkbox"], $array);``` to convert ! ```parse_str``` wrote in php Core and run fast.... – PersianMan Oct 05 '18 at 09:03