How can I convert a string to array? - php

I have a string like this:
$str = '[{"file_id":"AgADBAADX6oxGyqs0FJLW3rZ3g6_fDnO-RkABB0pg6HTwdv7EqUBAAEC","file_size":1347,"file_path":"photos\/file_2.jpg","width":90,"height":75},{"file_id":"AgADBAADX6oxGyqs0FJLW3rZ3g6_fDnO-RkABIMbRhad2WVdE6UBAAEC","file_size":17588,"width":320,"height":265},{"file_id":"AgADBAADX6oxGyqs0FJLW3rZ3g6_fDnO-RkABHSo-WKlRRfBEaUBAAEC","file_size":18480,"width":330,"height":273}]';
How can I access items in it?
I can use regex to select them, something like /"file_id":"(.*?)"/. But that's not clean at all. Is there any approach to make a array (or an object) of string above?

It's a json string.
You need to decode it with json_decode.
The second argument (true) is to make it an array.
$str = '[{"file_id":"AgADBAADX6oxGyqs0FJLW3rZ3g6_fDnO-RkABB0pg6HTwdv7EqUBAAEC","file_size":1347,"file_path":"photos\/file_2.jpg","width":90,"height":75},{"file_id":"AgADBAADX6oxGyqs0FJLW3rZ3g6_fDnO-RkABIMbRhad2WVdE6UBAAEC","file_size":17588,"width":320,"height":265},{"file_id":"AgADBAADX6oxGyqs0FJLW3rZ3g6_fDnO-RkABHSo-WKlRRfBEaUBAAEC","file_size":18480,"width":330,"height":273}]';
$arr = json_decode($str, true);
Var_dump($arr);
https://3v4l.org/9BFIC

Explode(“,{”, $str); will work for the above.
You will get array value for each file.

Related

Convert string like this to php array?

I want to convert a string like this code below to array, How can I do this plz?
$icon = '{``font``:``feather``,``icon``:``feather-facebook``}';
Is there any way by using json_decode or something like this?
Thanks.
The input string is not proper json format
When you correct json syntax then you can just json_decode it
$icon = '{"font":"feather","icon":"feather-facebook"}';
$array = json_decode($icon);
var_dump($array);

Convert PHP string to JSON array

Problem:
Converting a PHP string to a JSON array.
I have a string in PHP that looks like this:
intelligence skin weight volume
Desired output:
Is there a way in PHP where I can convert it so it looks like this instead:
["skin", "intelligence", "weight", "volume"]
I looked at json_encode() but that only put double quotes around the keywords.
If you want to create JSON array, you have to first explode your input string into an array.
Try with:
$input = 'intelligence skin weight volume';
$output = json_encode(explode(' ', $input));
first explode the string based on space. then u get an array containing individual words.then json_encode the array
$string="intelligence skin weight volume";
$array=explode(' ',$string);
$json=json_encode($array);
Check json_encode
This function would expect array and will convert array into json. Then use json_decode() to revert json to an array
$str="intelligence skin weight volume";
$arr=explode(' ',$str);
$json=json_encode($arr);
explode() used to split a string by a delimiter(in this senarion it is " ") Now you can encode the returend array as json.
Use json_encode
$jsonVal = json_encode(explode(' ', "intelligence skin weight volume"));

counting the number of arrays in a php decoded string

I have two json decoded strings:
{"Coords":[{"Accuracy":"66","Latitude":"88","Longitude":"99","Timestamp":"100"}]}
and I have another string
{"Coords":[{"Accuracy":"222","Latitude":"333","Longitude":"444","Timestamp":"2013"},{"Accuracy":"3434","Latitude":"565","Longitude":"676","Timestamp":"7878"}]}.
Is there a way to be able to echo that the first string has 1 array and the second string has 2? My method was as following:
$Json_String=($_POST['Json']); $Json_Decoded= json_decode($Json_String, true); echo count(json_decode($Json_String, true));
where $Json_String is just what I'm pasting into a text field for now for testing purposes.
Do,
json_decode($jsonString, true);
for each string that will return you array. You can then count the length of array easily.
if you just want to kown the length try this:
echo substr_count (' {"Coords":[{"Accuracy":"222","Latitude":"333","Longitude":"444","Timestamp":"2013"},{"Accuracy":"3434","Latitude":"565","Longitude":"676","Timestamp":"7878"}]}.','Accuracy');

is string an array in php

you can do numeric index in string like in array.
ex.
$text = "esenihc gnikcuf yloh";
echo $text[0];
echo $text[1];
echo $text[2];
...................
...................
...................
But if you put string in print_r() not same will happen like in array and you cant do count() with string.
I read the documentation and it says.
count()
return 1 if not an array in the parameter
print_r()
if string is in parameter it just prints that string.
this is not the exact word but something like this.
Why both these functions dont treat string same as an array?
So final question is string an array?
Unlike for example C, PHP has an inbuilt string datatype. The string datatype allows you array-like access to the single characters in the string but will always be a string. So if you pass it to a function that accepts the mixeddatatype this function will determine the datatype of the passed argument and treat it that way. That is way print_r() will print it in the way it was programmed to output strings and not like an array.
If you want a function that works does the same as count for arrays have a look at strlen.
If you want you can "turn" your string into an array through str_split.
A string is an array if you treat it as an array, eg: echo $text[0], but print_r Prints human-readable information about a variable, so it will output that variable.
It's called Type Juggling
$a = 'car'; // $a is a string
$a[0] = 'b'; // $a is still a string
echo $a; // bar
To count a string's length use strlen($string) then you can for a for()
no a string is no array
A string is series of characters, where a character is the same as a byte and An array in PHP is actually an ordered map. A map is a type that associates values to keys.
simply everything in the sense every variable in PHP is an array.
Maybe too late but:
<?php
$text = "esenihc gnikcuf yloh";
$arrText = explode(" ", $text);
foreach($arrText as $word) {
echo $word . "<br>";
}
?>

Elegant solution to read and transform query string in php?

I have a query string such as this:
file.php?search=keyword+here&genre1=1&genre4=1&genre19=1&genre181&director=436&actor=347&search_rating=3
I need to extract all the genres mentioned in the string, in this case its
genre1, genre4, genre19 and genre18
and output them into a string such as
ge1_ge4_ge19_ge18
What would be a good solution for this?
If you want the parameters passed by query string to the currently executing script then you simply need:
$genres = preg_grep('!^genre!', array_keys($_GET));
$out = implode('_', $genres);
Here you're filtering out all the parameters that start with genre using preg_grep() and getting a list of parameter names using array_keys().
If you have a URL you need to parse then use this snippet:
$url = 'file.php?search=keyword+here&genre1=1&genre4=1&genre19=1&genre181&director=436&actor=347&search_rating=3';
$query = parse_url($url, PHP_URL_QUERY);
parse_str($query, $params);
$genres = preg_grep('!^genre!', array_keys($params));
echo implode('_', $genres);
The difference here is that you use parse_url() to extract the query string and parse_str() to parse the query string.
Output:
genre1_genre4_genre19_genre181
parse_str() with the optional $arr argument is specifically built for exploding a query string properly:
Parses str as if it were the query string passed via a URL and sets variables in the current scope.
It can even deal with array arguments.
http_build_query() can glue an array back together with a custom $arg_separator but to get the output specifically as you want it, you will have to manually iterate through the arguments to make the transformation.
You could explode on the '=' then join on '_'.

Categories