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 );
Related
Im looking for the way to add curly braces {} on my Array of string :
print_r(json_encode($temp));
temp = [{"Red":1,"Blue":2,"Green":2}]
Im creating that values with :
$query_final = (my query);
$query = $this->db->query($query_final)->result_array();
$res = array_count_values(array_column($query, 'status'));
array_push($temp, $res);
print_r(json_encode($temp));
become:
print_r(json_encode($temp));
temp = [{"Red": "1"},{"Idle":"2"},{"Overload":"2"}]
So far i've tried to use implode :
$temp = implode(",", $temp);
print_r(json_encode($temp));
but it just giving the error, is there any way to do the right thing ?
array_count_values() returns a list of the values and the number of times they occur, so just using array_push() will add this entire array as 1 item and give you the results your getting.
Instead, you can add the results one at a time to the $temp array and get the results your after...
$temp = [];
$res = array_count_values(array_column($query, 'status'));
foreach ( $res as $key=>$item ) {
$temp[] = [$key => $item];
}
print_r(json_encode($temp));
Decode your json with json_decode($temp, true);
You can use json_encode on an array to get a JSON. Like so:
$temp = ['Red' => 1,
'Blue' => 2,
'Green' => 2
];
print_r(json_encode($temp)); // {"Red":1,"Blue":2,"Green":2}
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!
Is there a way of turning this:
network={
ssid="tele2-ssid-66577"
#psk="testtest2"
psk=8308d8e34c60fe471fda6837ab5821694e8cf51a655f24295797df33d02df6e9
}
into an object or an array with php?
I tried json_decode with no result.
------------- UPDATE:
the end goal is to extract only the psk key, I just thought turning it into an object/array would be the easiest thing to do rather than meddling with regular expressions or fiddling with the string, but maybe it's not possible...
I ran it through regex and then some processing
$str = 'network={
ssid="tele2-ssid-66577"
#psk="testtest2"
psk=8308d8e34c60fe471fda6837ab5821694e8cf51a655f24295797df33d02df6e9
}';
$output = array();
if (preg_match_all('/(([^=]+)=\{|\s+([^#]+)=(.*))/', $str, $match) and sizeof($match[2]) > 2) {
$output[$match[2][0]] = array();
for ($i=1; $i<sizeof($match[2]); $i++) {
$key = trim($match[3][$i]);
$value = trim($match[4][$i]);
// remove outer double quotes
if (preg_match('/^"(.*)"$/', $value, $match2)) $value = $match2[1];
// save
$output[$match[2][0]][$key] = $value;
}
}
print_r($output);
Giving the output:
Array
(
[network] => Array
(
[ssid] => tele2-ssid-66577
[psk] => 8308d8e34c60fe471fda6837ab5821694e8cf51a655f24295797df33d02df6e9
)
)
To create array from 1 php variable Why out put not same array ?
in this code i create array using php variable
<?PHP
$xxx = "'Free', 'Include', 'Offer', 'Provide'";
$xxx_array = array($xxx);
echo '<pre>'; print_r($xxx_array); echo '</pre>';
?>
and echo is
Array
(
[0] => 'Free', 'Include', 'Offer', 'Provide'
)
how to echo like this
Array
(
[0] => Free
[1] => Include
[2] => Offer
[3] => Provide
)
<?php
$xxx = "'Free', 'Include', 'Offer', 'Provide'";
// Split by ","
$separatedValues = explode(',', $xxx);
// Remove the single quotation marks
for($i = 0; $i < count($separatedValues); ++$i) {
$separatedValues[$i] = str_replace("'", '', $separatedValues[$i]);
}
var_dump($separatedValues);
?>
It is all about the explode() (http://de.php.net/explode) function.
Read up on the explode() function. The below code accomplishes what you ask.
<?PHP
$xxx = "'Free', 'Include', 'Offer', 'Provide'";
$xxx_array = array(explode(",", $xxx);
echo '<pre>';
print_r($xxx_array);
echo '</pre>';
?>
If you want to mimic actually creating the array (and not having the values quoted within the array), use this:
$xxx_array = array_map( function( $el) { return trim( $el, "' "); }, explode(',', $xxx));
This trims the ' and spaces from the beginning and ends of the elements after converting the string to an array.
I have this the values of in my array as
$itsthere = (item1-0-100, item2-0-50, item3-0-70, item4-0-50, item5-0-100);
If the user enter the value item3 he has to get 70 which is present in array. I tried alot using explode but its not showing proper value. Can any one help me.
Try with:
$itsthere = array(
'item1-0-100',
'item2-0-50',
'item3-0-70',
'item4-0-50',
'item5-0-100'
);
$search = 'item3';
$output = '';
foreach ( $itsthere as $value ) {
if ( strpos($search . '-', $value) === 0 ) {
$output = explode('-', $value)[2];
break;
}
}
When you say item3 are you refering to the third position or the item3 as array key? I think you can create a assoc array and make item names as key
$isthere = array('item1' => '0-100', 'item2' => '0-50' ,'item3' => '0-70', ....,);
echo $isthere['item3']; // This would give you the value.
If you only want to know if this key is in the array use array_key_exists.
Try this :
$item = 'item3';
$itsthere = array('item1-0-100', 'item2-0-50', 'item3-0-70', 'item4-0-50', 'item5-0-100');
foreach($itsthere as $there)
{
$exp = explode('-',$there);
if($exp[0] == 'item3') {
echo $val = $exp[2];
};
}