Sterlingman
Sterlingman

Reputation: 81

Flipping An Array without removing unique keys?

I'm trying to set user permissions, they are stored as an array in the database.. This is the current output from my html form...

{
"where_to_buy": "true",
"spec_sheet": "true",
"dwg_access": "true",
"bim_access": "true",
"product_prices": "true",
"portal_access": "true",
"save_quote": "true",
"request_drawings": "true",
"place_order": "true",
"special_offer": "true"
}

However I need it to be formatted like so:

{
"where_to_buy": true,
"spec_sheet": true,
"dwg_access": true,
"bim_access": true,
"product_prices": true,
"portal_access": true,
"save_quote": true,
"request_drawings": true,
"place_order": true,
"special_offer": true
}

How do I stop or convert my html form submission from strings to just true or false values?

Upvotes: 0

Views: 46

Answers (2)

danjam
danjam

Reputation: 1062

You can map values with array_walk

This also allows you to add more than true/false if required later

// from json   
$yourArray = json_decode($yourJSON, true);

// map values
array_walk($yourArray, function(&$v) {
    $map = array(
        'true' => true,
        'false' => false
        // more as needed
    );

    if ( isset($map[$v]) ) {
        $v = $map[$v];
    }
});

// back to json
$output = json_encode($yourArray);

Edit: both at once, see comments

$yourArray = json_decode($yourJSON, true);
$yourFormattedArray = array();
$map = array(
    'true' => true,
    'false' => false
    // more as needed
);

foreach ($yourArray as $key => $val ) {
    if ( isset($map[$val]) ) {
        $val = $map[$val];
    }
    $yourFormattedArray[str_replace('_', '.', $key)] = $val;
}

$yourFinalArray = json_encode($yourFormattedArray);

Upvotes: 1

Narendrasingh Sisodia
Narendrasingh Sisodia

Reputation: 21422

You can simply use json_decode along with array_map like as

echo json_encode(array_map(function($v) {
        if ($v == "true") {
            return true;
        } else {
            return false;
        }
    }, json_decode($json, true)));

Upvotes: 4

Related Questions