I have comma separated value pairs and I would like to convert it to associative array in php.
Example:
{
Age:30,
Weight:80,
Height:180
}
Converted to:
Echo $obj['Weight']; // 80
Does it make a difference that my values are not in inverted commas? I mean:
Weight:80
Vs
Weight:'80'
P.S. I've posted from a phone, so I don't have a lot of fancy markup available to make this question look more presentable.
http://php.net/manual/en/function.json-decode.php
It's an JSON object which you would like to convert to an array.
$string = '{ "Age":30, "Weight":80, "Height":180 }';
$array = json_decode($string, true);
echo $array['Age']; // returns 30
Provided that the given string is a valid JSON.
UPDATE
If that doesn't work because the string doesn't contain a valid JSON object (because I see the keys are missing double quotes), you could execute this regex function first:
$string = "{ Age:30, Weight:80, Height:180 }";
$json = preg_replace('/(?<!")(?<!\w)(\w+)(?!")(?!\w)/u', '"$1"', $string); // fix missing quotes
$obj = json_decode($json, true);
echo $obj['Age']; // returns 30
When using the regex above, make sure the string doesn't contain any quotes at all. So make sure that not some keys have quotes and some not. If so, first get rid of all quotes before executing the regex:
str_replace('"', "", $string);
str_replace("'", "", $string);
You can get all values in an array by using this basic example:
// your string
$string = "{
Age:30,
Weight:80,
Height:180
}";
// preg_match inside the {}
preg_match('/\K[^{]*(?=})/', $string, $matches);
$matchedResult = $matches[0];
$exploded = explode(",",$matchedResult); // explode with ,
$yourData = array();
foreach ($exploded as $value) {
$result = explode(':',$value); // explode with :
$yourData[$result[0]] = $result[1];
}
echo "<pre>";
print_r($yourData);
Result:
Array
(
[Age] => 30
[Weight] => 80
[Height] => 180
)
Explanation:
(?<=}) look behind asserts.
K[^{] matches the opening braces and K tells what was matched.
Related
I have a string of this type:
string(11) "2=OK, 3=OK"
from a text file. But I would like to convert it into an array of keys this type :
array (
[2] => Ok
[3] => Ok
)
I was wondering how we could do that in PHP.
Note:- I normally use explode() and str_split() for the conversions string into array but in this case I don't know how to do it.
use explode(), foreach() along with trim()
<?php
$string = "2=OK, 3=OK" ;
$array = explode(',',$string);
$finalArray = array();
foreach($array as $arr){
$explodedString = explode('=',trim($arr));
$finalArray[$explodedString[0]] = $explodedString[1];
}
print_r($finalArray);
https://3v4l.org/ZsNY8
Explode the string by ',' symbol. You will get an array like ['2=OK', ' 3=OK']
Using foreach trim and explode each element by '=' symbol
You can use default file reading code and traverse it to achieve what you want,
$temp = [];
if ($fh = fopen('demo.txt', 'r')) {
while (!feof($fh)) {
$temp[] = fgets($fh);
}
fclose($fh);
}
array_walk($temp, function($item) use(&$r){ // & to change in address
$r = array_map('trim',explode(',', $item)); // `,` explode
array_walk($r, function(&$item1){
$item1 = explode("=",$item1); // `=` explode
});
});
$r = array_column($r,1,0);
print_r($r);
array_walk — Apply a user supplied function to every member of an array
array_map — Applies the callback to the elements of the given arrays
explode — Split a string by a string
Demo.
You can use preg_match_all along with array_combine, str_word_count
$string = "2=OK, 3=OK" ;
preg_match_all('!\d+!', $string, $matches);
$res = array_combine($matches[0], str_word_count($string, 1));
Output
echo '<pre>';
print_r($res);
Array
(
[2] => OK
[3] => OK
)
LIVE DEMO
I have this JSON
[size: null, color: "white"]
Which send to the server via post method.
I try
$your_json_string = json_decode($your_json_string, TRUE)
and
$your_json_string = html_entity_decode($your_json_string);
$your_json_string = json_decode($your_json_string, true);
With print_r($your_json_string); I get: null.
With echo json_last_error(); I get: 4.
Any ideas on how I can solve this?
1) that is a json array [] not an object {}.
2) it will want property names quoted.
$String = <<< LOL
{"size": null, "color": "white"}
LOL;
print_r(json_decode($String,TRUE));
then you get
Array
(
[size] =>
[color] => white
)
If you have a wrong json string and you don't know how it will convert json to array in php. Example Below:
$string = '{test ing,test ingredients,test ingredients3,test ingredients4,test ingredients5}';
Trim your json string and remove non required data.
$string = ltrim($string, '{');
$string = rtrim($string, '}');
Remove comma from string and get normal php array
$newSting = explode(',', $string);
Now you can loop through your data
foreach ($newSting as $key => $value) {
echo $value;
}
I have a json which seems to be invalid
{
"systemId": 4424,
"professional":88928,
"gate":532,
"mock":02,
"wish":"this",
"transaction_id":"eeases-323fasfse-asdfe33",
"channel": "API",
}
So hence, it cannot be converted to an array in php, i tried json lint and it shows an error at 02.
After some research I came to know that value starting from 0 in json is invalid.
When I surround 02 with double quotes "", than it was successfully converted to array using json_decode.
So I am wondering, how can I add quotes to number all assuming json to be a string.
<?php
$data = '{
"systemId":4424,
"professional":88928,
"gate":532,
"mock":02,
"wish":"this",
"transaction_id":"eeases-323fasfse-asdfe33",
"channel": "API",
}';
$data = str_replace('}', '', str_replace('{', '', $data));
echo '<pre>';
$t = preg_match_all("/(?<=\:)(.*?)(?=\,)/", $data, $matches);
$i=0;
foreach($matches[1] as $key => $value){
if(is_numeric($value)){
$matches[1][$i] = '"'.$value .'"';
}
$data = str_replace($value, $matches[1][$i], $data);
$i++;
}
$data = rtrim(trim($data),','); //remove last comma
$data = '{'.$data .'}';
$data = json_decode($data,true);
print_r($data);
Dirty solution, and i agree 100% with the idea to "fix" your json before you get the response.
If you really really have to go that way to fix your json inside the code the above code will help you in that.
The reason i am trimming the curly brackets at first is to have a more clear string with the data. I concatenate them in the final format when i have done everything needs to be done.
The result of the code is :
Array
(
[systemId] => 4424
[professional] => 88928
[gate] => 532
[mock] => 02
[wish] => this
[transaction_id] => eeases-323fasfse-asdfe33
[channel] => API
)
An array decoded from the valid json
I am using a explode and str_replace on the get parameter of the query string URL. My goal is to split the strings by certain characters to get to the value in the string that I want. I am having issues. It should work but doesn't.
Here are two samples of links with the query strings and delimiters I'm using to str_replace.
http://computerhelpwanted.com/jobs/?occupation=analyst&position=data-analyst
as you can see the URL above parameter is position and the value is data-analyst. The delimiter is the dash -.
http://computerhelpwanted.com/jobs/?occupation=analyst&position=business+systems+analyst
and this URL above uses same parameter position and value is business+systems+analyst. The delimiter is the + sign.
The value I am trying to get from the query string is the word analyst. It is the last word after the delimiters.
Here is my code which should do the trick, but doesn't for some reason.
$last_wordPosition = str_replace(array('-', '+')," ", end(explode(" ",$position)));
It works if the delimiter is a + sign, but fails if the delimiter is a - sign.
Anyone know why?
You have things in the wrong order:
$last_wordPosition = end(explode(" ", str_replace(array('-', '+'), " ", $position)));
You probably want to split it up so as to not get the E_STRICT error when not passing an variable to end:
$words = explode(" ", str_replace(array('-', '+'), " ", $position));
echo end($words);
Or something like:
echo preg_replace('/[^+-]+(\+|-)/', '', $position);
As #MarkB suggested you should use parse_url and parse_str since it is more appropriate in your case.
From the documentation of parse_url:
This function parses a URL and returns an associative array containing any of the various components of the URL that are present.
From the documentation of parse_str:
Parses str as if it were the query string passed via a URL and sets variables in the current scope.
So here is what you want to do:
$url1 = 'http://computerhelpwanted.com/jobs/?occupation=analyst&position=data-analyst';
$url2 = 'http://computerhelpwanted.com/jobs/?occupation=analyst&position=business+systems+analyst';
function mySplit($str)
{
if (preg_match('/\-/', $str))
$strSplited = split('-', $str);
else
$strSplited = split(' ', $str);
return $strSplited;
}
parse_str(parse_url($url1)['query'], $output);
print_r($values = mySplit($output['position']));
parse_str(parse_url($url2)['query'], $output);
print_r($values = mySplit($output['position']));
OUTPUT
Array
(
[0] => data
[1] => analyst
)
Array
(
[0] => business
[1] => systems
[2] => analyst
)
You said that you needed the last element of those values. Therefore you could find end and reset useful:
echo end($values);
reset($values);
Answering my own question to show how I ended up doing this. Seems like way more code than what the accepted answer is, but since I was suggested to use parse_url and parse_str but couldn't get it working right, I did it a different way.
function convertUrlQuery($query) {
$queryParts = explode('&', $query);
$params = array();
foreach ($queryParts as $param) {
$item = explode('=', $param);
$params[$item[0]] = $item[1];
}
return $params;
}
$arrayQuery = convertUrlQuery($_SERVER['QUERY_STRING']); // Returns - Array ( [occupation] => designer [position] => webmaster+or+website-designer )
$array_valueOccupation = $arrayQuery['occupation']; // Value of occupation parameter
$array_valuePosition = $arrayQuery['position']; // Value of position parameter
$split_valuePosition = explode(" ", str_replace(array('-', '+', ' or '), " ", $array_valuePosition)); // Splits the value of the position parameter into separate words using delimeters (- + or)
then to access different parts of the array
print_r($arrayQuery); // prints the array
echo $array_valueOccupation; // echos the occupation parameters value
echo $array_valuePosition; // echos the position parameters value
print_r($split_valuePosition); // prints the array of the spitted position parameter
foreach ($split_valuePosition as $value) { // foreach outputs all the values in the split_valuePosition array
echo $value.' ';
}
end($split_valuePosition); // gets the last value in the split_valuePosition array
implode(' ',$split_valuePosition); // puts the split_valuePosition back into a string with only spaces between each word
which outputs the following
arrayQuery = Array
(
[occupation] => analyst
[position] => data-analyst
)
array_valueOccupation = analyst
array_valuePosition = data-analyst
split_valuePosition = Array
(
[0] => data
[1] => analyst
)
foreach split_valuePosition =
- data
- analyst
end split_valuePosition = analyst
implode split_valuePosition = data analyst
How to remove any special character from php array?
I have array like:
$temp = array (".com",".in",".au",".cz");
I want result as:
$temp = array ("com","in","au","cz");
I got result by this way:
$temp = explode(",",str_replace(".","",implode(",",$temp)));
But is there any php array function with we can directly remove any character from all values of array? I tried and found only spaces can be removed with trim() but not for any character.
Use preg_replace function. This will replace anything that isn't a letter, number or space.
SEE DEMO
<?php
$temp = array (".com",".in",".aus",".cz");
$temp = preg_replace("/[^a-zA-Z 0-9]+/", "", $temp );
print_r($temp);
//outputs
Array
(
[0] => com
[1] => in
[2] => aus
[3] => cz
)
?>
I generaly make a function
function make_slug($data)
{
$data_slug = trim($data," ");
$search = array('/','\\',':',';','!','#','#','$','%','^','*','(',')','_','+','=','|','{','}','[',']','"',"'",'<','>',',','?','~','`','&',' ','.');
$data_slug = str_replace($search, "", $data_slug);
return $data_slug;
}
And then call it in this way
$temp = array (".com",".in",".au",".cz");
for($i = 0; $i<count($temp); $i++)
{
$temp[$i] = make_slug($temp[$i]);
}
print_r($temp);
Each value of $temp will then become free of special characters
See the Demo
As a solution to your problem please execute the following code snippet
$temp = array (".com",".in",".au",".cz");
function strip_special_chars($v)
{
return str_replace('.','',$v);
}
$result[]=array_map('strip_special_chars',$temp);
Actually trim() can trim any character(s) you wish if you provide the 2nd argument (character mask). As it's name implies, this will only remove characters from the beginning and end of the string. In your case ltrim() may be more appropriate.
You can use array_map() and ltrim() together with a third parameter for the character mask like this:
$temp = array_map('ltrim', $temp, array_fill(0, count($temp), '.'));
The third parameter should be an array of arguments matching the length of the array you're processing, which is why I used array_fill() to create it.