How can I turn a string below into an array?
pg_id=2&parent_id=2&document&video
This is the array I am looking for,
array(
'pg_id' => 2,
'parent_id' => 2,
'document' => ,
'video' =>
)
You want the parse_str function, and you need to set the second parameter to have the data put in an array instead of into individual variables.
$get_string = "pg_id=2&parent_id=2&document&video";
parse_str($get_string, $get_array);
print_r($get_array);
Sometimes parse_str() alone is note accurate, it could display for example:
$url = "somepage?id=123&lang=gr&size=300";
parse_str() would return:
Array (
[somepage?id] => 123
[lang] => gr
[size] => 300
)
It would be better to combine parse_str() with parse_url() like so:
$url = "somepage?id=123&lang=gr&size=300";
parse_str( parse_url( $url, PHP_URL_QUERY), $array );
print_r( $array );
Using parse_str().
$str = 'pg_id=2&parent_id=2&document&video';
parse_str($str, $arr);
print_r($arr);
If you're having a problem converting a query string to an array because of encoded ampersands
&
then be sure to use html_entity_decode
Example:
// Input string //
$input = 'pg_id=2&parent_id=2&document&video';
// Parse //
parse_str(html_entity_decode($input), $out);
// Output of $out //
array(
'pg_id' => 2,
'parent_id' => 2,
'document' => ,
'video' =>
)
Use http://us1.php.net/parse_str
Attention, its usage is:
parse_str($str, &$array);
not
$array = parse_str($str);
Please note that the above only applies to PHP version 5.3 and earlier. Call-time pass-by-reference has been removed in PHP 5.4.
There are several possible methods, but for you, there is already a built-in parse_str function:
$array = array();
parse_str($string, $array);
var_dump($array);
This is a one-liner for parsing a query from the current URL into an array:
parse_str($_SERVER['QUERY_STRING'], $query);
You can try this code:
<?php
$str = "pg_id=2&parent_id=2&document&video";
$array = array();
parse_str($str, $array);
print_r($array);
?>
Output:
Array
(
[pg_id] => 2
[parent_id] => 2
[document] =>
[video] =>
)
You can use the PHP string function parse_str() followed by foreach loop.
$str="pg_id=2&parent_id=2&document&video";
parse_str($str,$my_arr);
foreach($my_arr as $key=>$value){
echo "$key => $value<br>";
}
print_r($my_arr);
But PHP already comes with a built in $_GET function. this will convert it to the array by itself.
try print_r($_GET) and you will get the same results.
This is the PHP code to split a query in MySQL and SQL Server:
function splitquery($strquery)
{
$arrquery = explode('select', $strquery);
$stry = ''; $strx = '';
for($i=0; $i<count($arrquery); $i++)
{
if($i == 1)
{
echo 'select ' . trim($arrquery[$i]);
}
elseif($i > 1)
{
$strx = trim($arrquery[($i-1)]);
if(trim(substr($strx,-1)) != '(')
{
$stry = $stry . '
select ' . trim($arrquery[$i]);
}
else
{
$stry = $stry.trim('select ' . trim($arrquery[$i]));
}
$strx = '';
}
}
return $stry;
}
Example:
Query before
Select xx from xx select xx,(select xx) from xx where y=' cc'
select xx from xx left join (select xx) where (select top 1 xxx from xxx) oder by xxx desc";
Query after
select xx from xx
select xx,(select xx) from xx where y=' cc'
select xx from xx left join (select xx) where (select top 1 xxx from xxx) oder by xxx desc
For this specific question the chosen answer is correct but if there is a redundant parameter—like an extra "e"—in the URL the function will silently fail without an error or exception being thrown:
a=2&b=2&c=5&d=4&e=1&e=2&e=3
So I prefer using my own parser like so:
//$_SERVER['QUERY_STRING'] = `a=2&b=2&c=5&d=4&e=100&e=200&e=300`
$url_qry_str = explode('&', $_SERVER['QUERY_STRING']);
//arrays that will hold the values from the url
$a_arr = $b_arr = $c_arr = $d_arr = $e_arr = array();
foreach( $url_qry_str as $param )
{
$var = explode('=', $param, 2);
if($var[0]=="a") $a_arr[]=$var[1];
if($var[0]=="b") $b_arr[]=$var[1];
if($var[0]=="c") $c_arr[]=$var[1];
if($var[0]=="d") $d_arr[]=$var[1];
if($var[0]=="e") $e_arr[]=$var[1];
}
var_dump($e_arr);
// will return :
//array(3) { [0]=> string(1) "100" [1]=> string(1) "200" [2]=> string(1) "300" }
Now you have all the occurrences of each parameter in its own array, you can always merge them into one array if you want to.
Hope that helps!
Related
How can I turn a string below into an array?
pg_id=2&parent_id=2&document&video
This is the array I am looking for,
array(
'pg_id' => 2,
'parent_id' => 2,
'document' => ,
'video' =>
)
You want the parse_str function, and you need to set the second parameter to have the data put in an array instead of into individual variables.
$get_string = "pg_id=2&parent_id=2&document&video";
parse_str($get_string, $get_array);
print_r($get_array);
Sometimes parse_str() alone is note accurate, it could display for example:
$url = "somepage?id=123&lang=gr&size=300";
parse_str() would return:
Array (
[somepage?id] => 123
[lang] => gr
[size] => 300
)
It would be better to combine parse_str() with parse_url() like so:
$url = "somepage?id=123&lang=gr&size=300";
parse_str( parse_url( $url, PHP_URL_QUERY), $array );
print_r( $array );
Using parse_str().
$str = 'pg_id=2&parent_id=2&document&video';
parse_str($str, $arr);
print_r($arr);
If you're having a problem converting a query string to an array because of encoded ampersands
&
then be sure to use html_entity_decode
Example:
// Input string //
$input = 'pg_id=2&parent_id=2&document&video';
// Parse //
parse_str(html_entity_decode($input), $out);
// Output of $out //
array(
'pg_id' => 2,
'parent_id' => 2,
'document' => ,
'video' =>
)
Use http://us1.php.net/parse_str
Attention, its usage is:
parse_str($str, &$array);
not
$array = parse_str($str);
Please note that the above only applies to PHP version 5.3 and earlier. Call-time pass-by-reference has been removed in PHP 5.4.
There are several possible methods, but for you, there is already a built-in parse_str function:
$array = array();
parse_str($string, $array);
var_dump($array);
This is a one-liner for parsing a query from the current URL into an array:
parse_str($_SERVER['QUERY_STRING'], $query);
You can try this code:
<?php
$str = "pg_id=2&parent_id=2&document&video";
$array = array();
parse_str($str, $array);
print_r($array);
?>
Output:
Array
(
[pg_id] => 2
[parent_id] => 2
[document] =>
[video] =>
)
You can use the PHP string function parse_str() followed by foreach loop.
$str="pg_id=2&parent_id=2&document&video";
parse_str($str,$my_arr);
foreach($my_arr as $key=>$value){
echo "$key => $value<br>";
}
print_r($my_arr);
But PHP already comes with a built in $_GET function. this will convert it to the array by itself.
try print_r($_GET) and you will get the same results.
This is the PHP code to split a query in MySQL and SQL Server:
function splitquery($strquery)
{
$arrquery = explode('select', $strquery);
$stry = ''; $strx = '';
for($i=0; $i<count($arrquery); $i++)
{
if($i == 1)
{
echo 'select ' . trim($arrquery[$i]);
}
elseif($i > 1)
{
$strx = trim($arrquery[($i-1)]);
if(trim(substr($strx,-1)) != '(')
{
$stry = $stry . '
select ' . trim($arrquery[$i]);
}
else
{
$stry = $stry.trim('select ' . trim($arrquery[$i]));
}
$strx = '';
}
}
return $stry;
}
Example:
Query before
Select xx from xx select xx,(select xx) from xx where y=' cc'
select xx from xx left join (select xx) where (select top 1 xxx from xxx) oder by xxx desc";
Query after
select xx from xx
select xx,(select xx) from xx where y=' cc'
select xx from xx left join (select xx) where (select top 1 xxx from xxx) oder by xxx desc
For this specific question the chosen answer is correct but if there is a redundant parameter—like an extra "e"—in the URL the function will silently fail without an error or exception being thrown:
a=2&b=2&c=5&d=4&e=1&e=2&e=3
So I prefer using my own parser like so:
//$_SERVER['QUERY_STRING'] = `a=2&b=2&c=5&d=4&e=100&e=200&e=300`
$url_qry_str = explode('&', $_SERVER['QUERY_STRING']);
//arrays that will hold the values from the url
$a_arr = $b_arr = $c_arr = $d_arr = $e_arr = array();
foreach( $url_qry_str as $param )
{
$var = explode('=', $param, 2);
if($var[0]=="a") $a_arr[]=$var[1];
if($var[0]=="b") $b_arr[]=$var[1];
if($var[0]=="c") $c_arr[]=$var[1];
if($var[0]=="d") $d_arr[]=$var[1];
if($var[0]=="e") $e_arr[]=$var[1];
}
var_dump($e_arr);
// will return :
//array(3) { [0]=> string(1) "100" [1]=> string(1) "200" [2]=> string(1) "300" }
Now you have all the occurrences of each parameter in its own array, you can always merge them into one array if you want to.
Hope that helps!
I'm trying to find out if there's any function that would split a string like:
keyword=flower|type=outdoors|colour=red
to array:
array('keyword' => 'flower', 'type' => 'outdoors', 'colour' => 'red')
At the moment I built a custom function, which uses explode to first split elements with the separator | and then each of those with assignment symbol =, but is there perhaps a native function which would do it out of the box by specifying the string separator?
The function I've written looks like this:
public static function splitStringToArray(
$string = null,
$itemDivider = '|',
$keyValueDivider = '='
) {
if (empty($string)) {
return array();
}
$items = explode($itemDivider, $string);
if (empty($items)) {
return array();
}
$out = array();
foreach($items as $item) {
$itemArray = explode($keyValueDivider, $item);
if (
count($itemArray) > 1 &&
!empty($itemArray[1])
) {
$out[$itemArray[0]] = $itemArray[1];
}
}
return $out;
}
$string = "keyword=flower|type=outdoors|colour=red";
$string = str_replace('|', '&', $string);
parse_str($string, $values);
$values=array_filter($values); // Remove empty pairs as per your comment
print_r($values);
Output
Array
(
[keyword] => flower
[type] => outdoors
[colour] => red
)
Fiddle
Use regexp to solve this problem.
([^=]+)\=([^\|]+)
http://regex101.com/r/eQ9tW8/1
The issue is that your chosen format of representing variables in a string is non-standard. If you are able to change the | delimiter to a & character you would have (what looks like) a query string from a URL - and you'll be able to parse that easily:
$string = "keyword=flower&type=outdoors&colour=red";
parse_str( $string, $arr );
var_dump( $arr );
// array(3) { ["keyword"]=> string(6) "flower" ["type"]=> string(8) "outdoors" ["colour"]=> string(3) "red" }
I would recommend changing the delimiter at the source instead of manually replacing it with replace() or something similar (if possible).
I have this Variable :
$value = '"item_id"=>"null","parent_id"=>"none","depth"=>0,"left"=>"1","right"=>18';
And I want get item_id and other element from top Variable with Array method, so i write this :
$value_arr = array($value);
$item_id = $value_arr["item_id"];
but i get error Notice: Undefined index: item_id in file.php on line 115
but When i use this method i get fine result successfully :
$value_arr = array("item_id"=>"null","parent_id"=>"none","depth"=>0,"left"=>"1","right"=>18);
$item_id = $value_arr["item_id"];
How i can solve this problem ?
Note: i don't want use 2'nd method because my Variables is Dynamic
UPDATE:
Vincent answered that i must use json_decode and i want to ask another question for better way because my original string that i have is :
[
{"item_id":null,"parent_id":"none","depth":0,"left":"1","right":18},
{"item_id":"1","parent_id":null,"depth":1,"left":2,"right":7},
{"item_id":"3","parent_id":null,"depth":1,"left":2,"right":7}
]
With this information whats the better way for get item_id, parent_id and ... ?
$value = '"item_id"=>"null","parent_id"=>"none","depth"=>0,"left"=>"1","right"=>18';
Is not a PHP array, you will need to convert that to an array by exploding it on "=>" and "," and remove any extra "'s you find.
You should be using JSON however and using json_encode and json_decode
Use json_decode() with second parameter as TRUE to get an associative array as result:
$json = json_decode($str, TRUE);
for ($i=0; $i < count($json); $i++) {
$item_id[$i] = $json[$i]['item_id'];
$parent_id[$i] = $json[$i]['parent_id'];
// ...
}
If you want to do it using a foreach loop:
foreach ($json as $key => $value) {
echo $value['item_id']."\n";
echo $value['parent_id']."\n";
// ...
}
Demo!
You should use JSON encoding and use the json_decode method if you want something dynamic. JSON is a good standard for dynamic data.
http://php.net/manual/en/function.json-decode.php
I tested this for you:
<?php
$value = '"item_id"=>"null","parent_id"=>"none","depth"=>0,"left"=>"1","right"=>18';
eval("\$value_arr = array($value);");
print_r($value_arr);
?>
Please check. PHP::eval() is used. It worked.
This can be a solution you are looking for:
<?php
$value = '"item_id"=>"null","parent_id"=>"none","depth"=>0,"left"=>"1","right"=>18';
$arr = explode(',',$value);
foreach($arr as $val)
{
$tmp = explode("=>",$val);
$array[$tmp[0]] = $tmp[1];
}
print_r($array);
?>
And this will output something like:
Array ( ["item_id"] => "null" ["parent_id"] => "none" ["depth"] => 0 ["left"] => "1" ["right"] => 18 )
A quick and dirty solution could be:
$array = json_decode( '{' . str_ireplace( '=>', ':', $value ) . '}', true );
// Array ( [item_id] => null [parent_id] => none [depth] => 0 [left] => 1 [right] => 18 )
EDIT: In regards to the update of the question.
Your input is a json_encoded array. simply json_decode it and you're done.
json_decode( $value, true );
My query
$sql ="select tTrack from tblcourse where tCourseCode = 'AZURE'";
$rs = mysql_query($sql);
$row_rs_course_category = mysql_fetch_assoc($rs);
gives me value Array ( [tTrack] => MS,CLOUD )
but i need to conver that array to this format from PHP
Array ( [0] => MS [1] => CLOUD )
how do i do it in php
You can use explode function to get this.
$newValue = explode(",", $row_rs_course_category['tTrack']);
Use explode().
$value = explode(',',$row_rs_course_category['tTrack'] );
echo "<pre>";
print_r($value);
//Array ( [0] => MS [1] => CLOUD )
I think you can use explode function to achieve this
$array = array ( 'tTrack' => 'MS,CLOUD' );
$array1 = explode(',', $array['tTrack']);
var_dump($array1);
this will output
array(2) { [0]=> string(2) "MS" [1]=> string(5) "CLOUD" }
explode() can help you
try this
$array = explode("," , $row_rs_course_category['tTrack']);
print_r($array);
You can use PHP explode function: http://php.net/manual/en/function.explode.php
$newArr = explode(',', $row_rs_course_category['tTrack']);
print_r($newArr);
User Php explode() function:
Look on Below link :
http://php.net/manual/en/function.explode.php
$sql ="select tTrack from tblcourse where tCourseCode = 'AZURE'";
$rs = mysql_query($sql);
$row_rs_course_category = mysql_fetch_assoc($rs);
if(isset($row_rs_course_category['tTrack']) && $row_rs_course_category['tTrack'] != '')
{
$result = explode(',',$row_rs_course_category['tTrack'] );
echo "<pre>";
print_r($value);
}
array explode ( string $delimiter , string $string [, int $limit ] )
delimiter
The boundary string.
string
The input string.
limit
If limit is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string.
If the limit parameter is negative, all components except the last -limit are returned.
If the limit parameter is zero, then this is treated as 1.
Switch to sqli, and do what they said explode the array.
$your_array=Array ( 'tTrack' => "MS,CLOUD" );
$new_array=explode(",",$your_array['tTrack']);
print_r($new_array);
How can I turn a string below into an array?
pg_id=2&parent_id=2&document&video
This is the array I am looking for,
array(
'pg_id' => 2,
'parent_id' => 2,
'document' => ,
'video' =>
)
You want the parse_str function, and you need to set the second parameter to have the data put in an array instead of into individual variables.
$get_string = "pg_id=2&parent_id=2&document&video";
parse_str($get_string, $get_array);
print_r($get_array);
Sometimes parse_str() alone is note accurate, it could display for example:
$url = "somepage?id=123&lang=gr&size=300";
parse_str() would return:
Array (
[somepage?id] => 123
[lang] => gr
[size] => 300
)
It would be better to combine parse_str() with parse_url() like so:
$url = "somepage?id=123&lang=gr&size=300";
parse_str( parse_url( $url, PHP_URL_QUERY), $array );
print_r( $array );
Using parse_str().
$str = 'pg_id=2&parent_id=2&document&video';
parse_str($str, $arr);
print_r($arr);
If you're having a problem converting a query string to an array because of encoded ampersands
&
then be sure to use html_entity_decode
Example:
// Input string //
$input = 'pg_id=2&parent_id=2&document&video';
// Parse //
parse_str(html_entity_decode($input), $out);
// Output of $out //
array(
'pg_id' => 2,
'parent_id' => 2,
'document' => ,
'video' =>
)
Use http://us1.php.net/parse_str
Attention, its usage is:
parse_str($str, &$array);
not
$array = parse_str($str);
Please note that the above only applies to PHP version 5.3 and earlier. Call-time pass-by-reference has been removed in PHP 5.4.
There are several possible methods, but for you, there is already a built-in parse_str function:
$array = array();
parse_str($string, $array);
var_dump($array);
This is a one-liner for parsing a query from the current URL into an array:
parse_str($_SERVER['QUERY_STRING'], $query);
You can try this code:
<?php
$str = "pg_id=2&parent_id=2&document&video";
$array = array();
parse_str($str, $array);
print_r($array);
?>
Output:
Array
(
[pg_id] => 2
[parent_id] => 2
[document] =>
[video] =>
)
You can use the PHP string function parse_str() followed by foreach loop.
$str="pg_id=2&parent_id=2&document&video";
parse_str($str,$my_arr);
foreach($my_arr as $key=>$value){
echo "$key => $value<br>";
}
print_r($my_arr);
But PHP already comes with a built in $_GET function. this will convert it to the array by itself.
try print_r($_GET) and you will get the same results.
This is the PHP code to split a query in MySQL and SQL Server:
function splitquery($strquery)
{
$arrquery = explode('select', $strquery);
$stry = ''; $strx = '';
for($i=0; $i<count($arrquery); $i++)
{
if($i == 1)
{
echo 'select ' . trim($arrquery[$i]);
}
elseif($i > 1)
{
$strx = trim($arrquery[($i-1)]);
if(trim(substr($strx,-1)) != '(')
{
$stry = $stry . '
select ' . trim($arrquery[$i]);
}
else
{
$stry = $stry.trim('select ' . trim($arrquery[$i]));
}
$strx = '';
}
}
return $stry;
}
Example:
Query before
Select xx from xx select xx,(select xx) from xx where y=' cc'
select xx from xx left join (select xx) where (select top 1 xxx from xxx) oder by xxx desc";
Query after
select xx from xx
select xx,(select xx) from xx where y=' cc'
select xx from xx left join (select xx) where (select top 1 xxx from xxx) oder by xxx desc
For this specific question the chosen answer is correct but if there is a redundant parameter—like an extra "e"—in the URL the function will silently fail without an error or exception being thrown:
a=2&b=2&c=5&d=4&e=1&e=2&e=3
So I prefer using my own parser like so:
//$_SERVER['QUERY_STRING'] = `a=2&b=2&c=5&d=4&e=100&e=200&e=300`
$url_qry_str = explode('&', $_SERVER['QUERY_STRING']);
//arrays that will hold the values from the url
$a_arr = $b_arr = $c_arr = $d_arr = $e_arr = array();
foreach( $url_qry_str as $param )
{
$var = explode('=', $param, 2);
if($var[0]=="a") $a_arr[]=$var[1];
if($var[0]=="b") $b_arr[]=$var[1];
if($var[0]=="c") $c_arr[]=$var[1];
if($var[0]=="d") $d_arr[]=$var[1];
if($var[0]=="e") $e_arr[]=$var[1];
}
var_dump($e_arr);
// will return :
//array(3) { [0]=> string(1) "100" [1]=> string(1) "200" [2]=> string(1) "300" }
Now you have all the occurrences of each parameter in its own array, you can always merge them into one array if you want to.
Hope that helps!