简体   繁体   中英

Convert a string of comma separated values to true/false array

I am trying to find a way to get the separated values and convert them to an array with false or true


$idValues = '111111,222222,333333';
$lubuvnaIDs = explode(",", $idValues);
$groups = '';

foreach($lubuvnaIDs as $row ){
        $groups .= $row .'=>'. true;
}

$newGroups = array($groups);


$dataSub = array (
        'interests' => $newGroups,
);

The final output of $newGroups should look like this:

$newGroups = array( 
        '111111'    => true,
        '222222'    => true,
        '333333'    => true
);

Instead of a loop, you can use array_fill_keys() with the list of values from the explode() . Setting the initial value to be true...

$newGroups = array_fill_keys(explode(",", $idValues), true);

How about just looping through the values and adding them to an array:

$idValues = '111111,222222,333333';
$lubuvnaIDs = explode(",", $idValues);

$newGroups = [];
foreach ($lubuvnaIDs as $id) {
    $newGroups[$id] = true;
}

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