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"));
Related
Is there any way to do this with preg_replace or other php code?
I have a string that looks like this:
[[10],[11],[2],[3],[5],[1],[10],[15],[20],[21],[14],[16],[17],[6],[9],[4]]
I want to display like this:
[[10,11],[2,3],[5,1],[10,15],[20,21],[14,16],[17,6],[9,4]]
So I replaced the "],[" part with str_replace
$xy1 = str_replace('],[', ',', $xy1);
And now looks like this:
[[10,11,2,3,5,1,10,15,20,21,14,16,17,6,9,4]]
But I need to add an extra "]" after every second number and an extra [ after every second comma ex.:
[[10,11],[2,3],[5,1]
A couple of possibilities:
The string is valid JSON, whether it was intended to be or not, so you can decode it, chunk the resulting array and re-encode it.
$result1 = json_encode(array_chunk(array_column(json_decode($string),0),2));
If you are producing the string in your previous code via json_encode it would be much better to just use array_chunk at that time, but if it's coming from some other source you obviously can't do that.
For this specific string, it may be less cumbersome to pair the numbers with a regex.
$result2 = preg_replace('/(\d+)\D+(\d+)/', '$1,$2', $string);
Or a combination of both ways, extract all the numbers and then chunk and encode.
preg_match_all('/\d+/', $string, $numbers);
$result3 = json_encode(array_chunk($numbers[0], 2), JSON_NUMERIC_CHECK);
This might help, extract the nested array values and then group them by pairs.
$newArray = array_chunk( array_column( $array, 0 ), 2 );
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.
I have made a system with browsing files; Now I have a problem:
My path string like this: A/Abba/2004/
I want to remove the text between the last 2 slashes (which is 2004 in this case).
So the output should look like A/Abba/
Can anyone help me as how to archive this in php?
Thanks.
If you try to remove last part of string you can do this this way:
$input = 'A/Abba/2014/';
$array = array_filter(explode('/', $input));
array_pop($array);
$correct = implode('/', $array);
array_filter removes empty strings from array
explode converts string to array by given delimiter
array_pop remove last item from given array
implode converts array to string using given 'glue'
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');
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>";
}
?>