get value from exploded string in php - php

I have custom cms database and get parameter from database and my result this is:
$param = 'param1="value1"|param2="value2"|param3="value3"|param4="value4"|param5="value5"'
but I need get param1 value or other value. I try use explode but my result this is:
$string = explode('|',$param);
result:
array (size=4)
0 => string 'param1="value1"'
1 => string 'param2="value2"'
2 => string 'param3="value3"'
3 => string 'param4="value4"'
4 => string 'param5="value4"'
I need get value this format:
$param->param1 = value1;

You also need to explode each of the substrings on =, and then map the results into an array:
$param = 'param1="value1"|param2="value2"|param3="value3"|param4="value4"|param5="value5"';
$params = explode('|', $param);
$results = [];
foreach ($params as $element) {
list($key, $value) = explode('=', $element, 2);
$results[$key] = json_decode($value);
}
echo $results['param1']; // value1
The call to json_decode might look a bit out of place here, but it's the quickest way to convert a quoted string into a native PHP string. The additional argument to the second explode call is to limit the result to two variables, in case the value itself contains an equals sign.

Try parse_str, you can then create an object using the array
<?php
$param = 'param1="value1"|param2="value2"|param3="value3"|param4="value4"|param5="value5"';
$params = array();
parse_str(str_replace('|', '&', $param), $params);
$params = (object) $params;
echo $params->param1;
?>

Nice and easy with a litte regex:
$param = 'param1="value1"|param2="value2"|param3="value3"|param4="value4"|param5="value5"';
$strings = explode('|', $param);
foreach ($strings as $string) {
preg_match('#param\d="(?<value>.+)"#', $string, $matches);
var_dump($matches['value']);
}
The regex #param\d="(?<value>.+)"# looks for param followed by a number then an equals, and we create a named capture group with ?<value> in the brackets.
The output from the var_dumps looks like this:
string(6) "value1"
string(6) "value2"
string(6) "value3"
string(6) "value4"
string(6) "value5"
Try it here https://3v4l.org/bomO7

When you've split the first part using '|', you can convert the rest as though it was a CSV field with '=' as the divider. This deals with quotes and other elements.
<?php
error_reporting ( E_ALL );
ini_set ( 'display_errors', 1 );
$param = 'param1="value1"|param2="value2"|param3="value3"|param4="value4"|param5="value5"';
$parms = explode('|', $param );
$values = [];
foreach ( $parms as $parm ) {
list($key, $value) = str_getcsv($parm, "=");
$values[$key] = $value;
}
print_r($values);

$param = 'param1="value1"|param2="value2"|param3="value3"|param4="value4"|param5="value5"';
$param = json_decode('{"' . str_replace(['=', '|'], ['":', ',"'], $param) . '}');
print_r($param);
This is just example. Don't use it in production :)

Use the following approach:
$param = 'param1="value1"|param2="value2"|param3="value3"|param4="value4"|param5="value5"';
$result = [];
foreach (explode('|', $param) as $item) {
list($k,$v) = explode('=', $item);
$result[$k] = trim($v, '"');
}
$result = (object) $result;
// as you wanted
print_r($result->param1); // value1

Related

Broke string into vars with variable position

I need to broke a string into some vars but its order is not fixed as the exemple:
$string = "name='John';phone='555-5555';city='oakland';";
$string2 = "city='oakland';phone='555-5555';name='John';";
$string3 = "phone='555-5555';name='John';city='oakland';";
so I need to broke the strings into:
$name
$phone
$city
if the position would be fixed i could use explode and call for the array key that i need like
$brokenString = explode("'",$string);
$name = $brokenString[1];
$phone = $brokenString[3];
$city = $brokenString[5];
however how could I do it with variable position??
One way to do it with sort to make the position same always for all string variables.
<?php
$string = "name='John';phone='555-5555';city='oakland';";
$string2 = "city='oakland';phone='555-5555';name='John';";
$string3 = "phone='555-5555';name='John';city='oakland';";
$array = explode(';',$string3);
sort($array);
$array = array_filter($array); # remove the empty element
foreach($array as $value){
$split = explode('=',$value);
$result[$split[0]] = $split[1];
}
extract($result); # extract result as php variables
echo "\$city = $city; \$name = $name; \$phone = $phone";
?>
EDIT: As using extract() is generally not a good idea.You can use simple foreach() instead of extract(),
foreach($result as $k => $v) {
$$k = $v;
}
WORKING DEMO: https://3v4l.org/RB8pT
There might be a simpler method, but what I've done is created an array $stringVariables which holds the exploded strings.
This array is then looped through and strpos is used in each element in the exploded string array to see if it contains 'city', 'phone', or 'name'. Depending on which one, it's added to an array which holds either all the names, cities or phone numbers.
$stringVariables = array();
$phones = array();
$names = array();
$cities = array();
$stringVariables[] = explode(";",$string);
$stringVariables[] = explode(";",$string2);
$stringVariables[] = explode(";",$string3);
foreach($stringVariables as $stringVariable) {
foreach($stringVariable as $partOfString) {
if(strpos($partOfString, "name=") !== false) {
$names[] = $partOfString;
}else if(strpos($partOfString, "city=") !== false) {
$cities[] = $partOfString;
}else if(strpos($partOfString, "phone=") !== false) {
$phones[] = $partOfString;
}
}
}
An alternative way is to convert it into something that can be parsed as a URL string.
First part is to change the values and , from 'John', to John& using a regex ('([^']+)'; which looks for a ' up to a ' followed by a ;), then parse the result (using parse_str())...
$string = "name='John';phone='555-5555';city='oakland';";
$string = preg_replace("/'([^']+)';/","$1&", $string);
echo $string.PHP_EOL;
parse_str( $string, $values );
print_r($values);
gives the output of
name=John&phone=555-5555&city=oakland&
Array
(
[name] => John
[phone] => 555-5555
[city] => oakland
)
or just using regex's...
preg_match_all("/(\w*)?='([^']+)';/", $string, $matches);
print_r(array_combine($matches[1], $matches[2]));

PHP: Convert string into array

I have an input string that has the following value:
"[2018-05-08][1][17],[2018-05-08][2][31],[2018-05-08][3][40],[2018-05-08][4][36],[2018-05-09][1][21]"
I want to convert this into a php array that looks something like this:
$date=2018-05-08;
$meal=1;
$option=17;
can someone help me please !
<?php
$data="[2018-05-08][1][17],[2018-05-08][2][31],[2018-05-08][3][40],[2018-05-08][4][36],[2018-05-09][1][21]";
$data=explode(',',$data);
foreach($data as $row){
preg_match_all('#\[(.*?)\]#', $row, $match);
$date=$match[1][0];
$meal=$match[1][1];
$option=$match[1][2];
}
This will store the values you need into the variables. I would suggest to store them in arrays and not variables so you can handle them outside of the foreach loop but that's up to you.
Simple parser for You
$arr1 = explode (",","[2018-05-08][1][17],[2018-05-08][2][31],[2018-05-08][3][40],[2018-05-08][4][36],[2018-05-09][1][21]"); // making array with elements like : [0] => "[2018-05-08][1][17]"
$arr2;
$i = 0;
foreach($arr1 as $item){
$temp = explode ("][",$item); // array with elements like [0] => "[2018-05-08", [1] => "1", [2] => "21]"
$arr2[$i]['date'] = substr( $temp[0], 1 ); // deleting first char( '[' )
$arr2[$i]['meal'] = $temp[1];
$arr2[$i]['option'] = substr($temp[2], 0, -1); // deleting last char( ']' )
$i++;
}
you cannot set array to variable .If you want convert string to array, i think my code example may help you:
$a= "[2018-05-08][1][17],[2018-05-08][2][31],[2018-05-08][3][40],[2018-05-08][4][36],[2018-05-09][1][21]";
$b= explode(",",$a );
foreach ($b as $key =>$value) {
$b[$key] = str_replace("[", " ", $b[$key]);
$b[$key] = str_replace("]", " ", $b[$key]);
$b[$key] =explode(" ",trim($b[$key]) );
}
print_r($b);
$results = array_map(
function ($res) {
$res = rtrim($res, ']');
$res = ltrim($res, '[');
return explode('][', $res);
},
explode(',', $yourString)
);
//get variables for first element of array
list($date, $meal, $option) = $results[0];

PHP how to extract info from json string wtihout knowing the keys

I am querying a service if a person have phone number(s) (also maybe not). I have a json string (as return value) like the following:
$json = '{"data":[{"tel1":"1102"},{"tel2":"3220"}],"found":true}';
I convert this string to json_decode() function.
$jd = json_decode($json);
Then I want to get the phone numbers only into an array without keys.
if($jd->found) {
$o2a = get_object_vars($json);
}
var_dump($o2a);
When I want to see what $o2a holds with var_dump() function, I get the following:
array (size=2)
'data' =>
array (size=2)
0 =>
object(stdClass)[2]
public 'tel1' => string '1219' (length=4)
1 =>
object(stdClass)[3]
public 'tel2' => string '2710' (length=4)
'found' => boolean true
I want to get only the phone numbers into an array at the end like:
$phones = array('1219', '2710');
What makes me stop doing this is that I do not know how many phone numbers one can have. Json array could consist of more or less elements.
$possibleJson1 = '{"data":[],"found":false}'; //no phone number found
$possibleJson2 = '{"data":[{"tel1":"1102"},{"tel2":"3220"},{"tel3":"1112"},{"tel4":"3230"}],"found":true}'; //4 phone numbers found
It may vary 0-to-n, so if it was a constant number I could create that array within a loop.
Some functions without any code :)
$json = '{"data":[{"tel1":"1102"},{"tel2":"3220"}],"found":true}';
$vals = array_values(array_reduce(json_decode($json, true)['data'], 'array_merge',[]));
var_dump($vals);
Convert it into an array and then you should be able to iterate it easily
$jd = json_decode($json, true);
$phones = array();
if(isset($jd['data']) && $jd['found']) {
foreach($jd['data'] as $key => $val) $phones[] = $val;
}
Instead of handling with an object, use the second parameter of the json_decode function so it would returned an array.
Check if the data and found keys exist.
Since you don't know what are the keys names, you can use array_values
Demo
.
$jd = json_decode($json, true);
if(isset($jd['data']) && isset($jd['found'])){
$telArr = $jd['data'];
$phones = array();
foreach($telArr as $tel){
$value = array_values($tel);
$phones[] = $value[0];
}
var_dump($phones);
}
Output:
array(2) {
[0]=>
string(4) "1102"
[1]=>
string(4) "3220"
}
Well, I would try something like that:
$json = '{"data":[{"tel1":"1102"},{"tel2":"3220"}],"found":true}';
$jd = json_decode($json);
$phones = [];
if ($jd->found && count($jd->data)) {
foreach ($jd->data as $key -> $value) {
$phones[] = $value;
}
}
Try as using in_array and simple foreach loop
$json = '{"data":[{"tel1":"1102"},{"tel2":"3220"}],"found":true}';
$arr = json_decode($json, true);
$result = array();
if (in_array(true, $arr)) {
foreach ($arr['data'] as $key => $value) {
foreach($value as $k => $v)
$result[] = $v;
}
}
print_r($result);
Fiddle

PHP explode array with 2 types of separators

I have this options array:
string(111) "colors:black;white;transparent;pink;"
how can I explode it so I get as a label first separator : and the rest in array as options? I have this so far:
$options= explode(";",$rows[0]);
$htm= '<ul class="product_opts">'.$lang['available_options'].'';
foreach ($options as $value) {
$row=mysql_fetch_row($result);
$htm.='<li style="text-align:left;font-weight:normal;">'.$value.'</li>';
}
$htm.= '</ul>';
}
echo $htm;
but it returns the label as option too..
$attributes="colors:black;white;transparent;pink;";
list($attribute, $values) = array_map(
function($value) {
return array_filter(explode(';', $value));
},
explode(':', $attributes)
);
var_dump($attribute);
var_dump($values);
$str = "colors:black;white;transparent;pink;";
list($label, $optionsStr) = explode(":", $str);
$optionsStr = rtrim($optionsStr, ";");
$options = explode(";", $optionsStr);
echo "<pre>";
print_r($label);
print_r($options);
Explode string by :. First token will be your label, second token your options.
Explode second token by ;, and you have your options in an array.
Try
$str = "colors:black;white;transparent;pink;";
$arr = explode(";",$str);
$key = explode(":",$arr[0]);
$arr[0] = $key[1];
unset($arr[sizeof($arr)-1]);
See demo here
use split to do like so
$options= split("[;|:]",$rows[0]);

converting array containing keys and values into string

I have an array it contains key and value. i would like to converting into a string.
array(
[business_type]=>'cafe'
[business_type_plural] => 'cafes'
[sample_tag]=>'couch'
[business_name]=>'couch cafe'
)
Expected Output:
business_type,cafe|business_type_plural,cafes|sample_tag,couch|business_name,couch cafe
NOTE:
I was searching in StackOverflow and found the below question and it has answer. I want exactly reverse one.
converting string containing keys and values into array
Try
$data = array();
foreach($arr as $key=>$value) {
$data[] = $key.','.$value;
}
echo implode('|',$data);
Another Solution:
function test_alter(&$item1, $key, $delimiter)
{
$item1 = "$key".$delimiter."$item1";
}
array_walk($arr, 'test_alter',',');
echo implode('|',$arr);
Use the foreach() function to go through the array and string the keys/values together...
Assuming your array is called $array
$result = "";
foreach($array as $key => $value){
$result .= $key . "," . $value . "|";
}
It's as simple as that.
EDIT - Thanks Nelson
After that, lost the last |
$result = rtrim($result, "|");
try this
$pieces=array();
foreach(array('key1'=>'val1', 'key2'=>'val2', 'key3'=>'val3') as $k=>$v)
{
$pieces[]=$k.','.$v;
}
echo implode('|', $pieces);

Categories