Reputation: 261
$var = {"4":true,"6":true,"8":true}
In The above string I want to get numbers into array.
Need: $var2 = [[0]=>4, [1]=>6, [2]=>8];
All response will be appreciated.
Upvotes: 2
Views: 63
Reputation: 9583
As i comment, use array_keys
, and json_decode
.
I don't believe that this question has an answer, So i did't answer it. But i did it later.
You have an json, so you need to use json_decode
now you jave an array where your keys are the desired value. so use array_keys.
$var = '{"4":true,"6":true,"8":true}';
$arr = json_decode($var, true);
echo '<pre>';
print_r(array_keys($arr));
Result:
Array
(
[0] => 4
[1] => 6
[2] => 8
)
Upvotes: 1
Reputation: 5141
First you decode the string using json_decode
, the second argument means that the function should return an associative array and non an array of objects. This willl help up get the array keys.
$decoded = json_decode($var, true);
You get the array keys with this loop and place them in $var
foreach($decoded as $key => $value){
$var2[] = $key;
}
Upvotes: 1
Reputation: 24276
You should use json_decode and array_keys to accomplish it:
array_keys(json_decode($var, true));
Upvotes: 3