Convert string into single array, PHP - php

I am working in a Laravel project. I want to convert a string into single array in efficient way.
String is
$string = txn_status=0|txn_msg=success|txn_err_msg=NA|clnt_txn_ref=969239|tpsl_bank_cd=470|tpsl_txn_id=192630337|txn_amt=1.00|clnt_rqst_meta={itc:NIC~TXN0001~122333~rt14154~8 mar 2014~Payment~forpayment}{custname:test}|tpsl_txn_time=26-12-2015 15:56:20|tpsl_rfnd_id=NA|bal_amt=NA|rqst_token=hdfs-df-jkfhskjfhsjkd|hash=jhdsfs54367jhf,
And I want output look like below format. It is a json format:-
[ txn_status: "0",
txn_msg : "success",
txn_err_msg: "NA",
.
.
.
hash: "XYZ" ]

You can split as like that try this:
$string = "txn_status=0|txn_msg=success|txn_err_msg=NA|clnt_txn_ref=969239|tpsl_bank_cd=470|tpsl_txn_id=192630337|txn_amt=1.00|clnt_rqst_meta={itc:NIC~TXN0001~122333~rt14154~8 mar 2014~Payment~forpayment}{custname:test}|tpsl_txn_time=26-12-2015 15:56:20|tpsl_rfnd_id=NA|bal_amt=NA|rqst_token=hdfs-df-jkfhskjfhsjkd|hash=jhdsfs54367jhf";
$firstArray = explode("|", $string);
foreach ($firstArray as $key => $value) {
$newArr = explode("=", $value);
$myRequiredArr[$newArr[0]] = $newArr[1];
}
echo "<pre>"; // just for formatting
print_r($myRequiredArr); // print your result
Result is:
Array
(
[txn_status] => 0
[txn_msg] => success
[txn_err_msg] => NA
[clnt_txn_ref] => 969239
[tpsl_bank_cd] => 470
[tpsl_txn_id] => 192630337
[txn_amt] => 1.00
[clnt_rqst_meta] => {itc:NIC~TXN0001~122333~rt14154~8 mar 2014~Payment~forpayment}{custname:test}
[tpsl_txn_time] => 26-12-2015 15:56:20
[tpsl_rfnd_id] => NA
[bal_amt] => NA
[rqst_token] => hdfs-df-jkfhskjfhsjkd
[hash] => jhdsfs54367jhf
)

You could use the preg_match_all in conjunction with the array_combine like this:
$string = "txn_status=0|txn_msg=success|txn_err_msg=NA|clnt_txn_ref=969239|tpsl_bank_cd=470|tpsl_txn_id=192630337|txn_amt=1.00|clnt_rqst_meta={itc:NIC~TXN0001~122333~rt14154~8 mar 2014~Payment~forpayment}{custname:test}|tpsl_txn_time=26-12-2015 15:56:20|tpsl_rfnd_id=NA|bal_amt=NA|rqst_token=hdfs-df-jkfhskjfhsjkd|hash=jhdsfs54367jhf";
preg_match_all("/([^|]+)=([^|]+)/", $string, $array);
$output = array_combine($array[1], $array[2]);
echo json_encode($output, JSON_PRETTY_PRINT);
http://ideone.com/eXf5K2
Or the preg_split like this:
$array = preg_split("/[|=]/", $string);
$output = [];
for ($i=0; $i<count($array); $i++) {
$output[$array[$i]] = $array[++$i];
}
http://ideone.com/Y5k5bV
Or a simplified version of #devpro's code:
$array = explode("|", $string);
$output = [];
foreach ($array as $v) {
list($key, $value) = explode("=", $v);
$output[$key] = $value;
}
http://ideone.com/svrj8S

You can use the combination of php functions explode , array_map and call_user_func_array like as
$string = "txn_status=0|txn_msg=success|txn_err_msg=NA|clnt_txn_ref=969239|tpsl_bank_cd=470|tpsl_txn_id=192630337|txn_amt=1.00|clnt_rqst_meta={itc:NIC~TXN0001~122333~rt14154~8 mar 2014~Payment~forpayment}{custname:test}|tpsl_txn_time=26-12-2015 15:56:20|tpsl_rfnd_id=NA|bal_amt=NA|rqst_token=hdfs-df-jkfhskjfhsjkd|hash=jhdsfs54367jhf";
$arr = array();
array_map(function($v)use(&$arr){ $a = explode("=",$v); return $arr[$a[0]] = $a[1];},explode('|',$string));
print_r($arr);
Working Demo

Related

Convert string into format array without remove coma PHP

I have string :
$string = "'id_konversi_aktivitas' => 'f4d943e7', 'nim' => '180218038'"
And I will convert to array like this :
$data = array($string);
But the result is like this :
array(1) { [0]=> string(87) "'id_konversi_aktivitas' => 'f4d943e7', 'nim' => '180218038'" }
I want result like this :
array(2) { ["id_konversi_aktivitas"] => "f4d943e7", ["nim"] => "180218038" }
there is no core PHP function to achieve what you are looking for. You can try in the following way.
$string = "'id_konversi_aktivitas' => 'f4d943e7', 'nim' => '180218038'";
$arrayStr = explode(',', $string);
$myArr = [];
foreach ($arrayStr as $arr) {
$eachArr = explode('=>', $arr);
$myArr[trim($eachArr[0])] = $eachArr[1];
}
print_r($myArr);
I made a function specifically for this problem, I hope it helps you out.
function stringToArray($string) {
$output = [];
$array = explode(",", $string);
foreach($array as $elem) {
$item = explode("=>", $elem);
$newItem = [
trim(str_replace("'", "", $item[0])) => $item[1]
];
array_push($output, $newItem);
}
return $output;
}
Here's how I used it
<?php
$string = "'id_konversi_aktivitas' => 'f4d943e7', 'nim' => '180218038'";
function stringToArray($string) {
$output = [];
$array = explode(",", $string);
foreach($array as $elem) {
$item = explode("=>", $elem);
$newItem = [
trim(str_replace("'", "", $item[0])) => $item[1]
];
array_push($output, $newItem);
}
return $output;
}
$data = stringToArray($string);
print_r($data[0]["id_konversi_aktivitas"]);
// >> 'f4d943e7'
Using regular expressions instead of a simple explode makes parsing a bit safer. preg_match_all returns the result in a form that returns the desired array with array_combine without a loop.
string = "'id_konversi_aktivitas' => 'f4d\'943e7', 'nim' => '180218038'";
preg_match_all("~'(.+?)' *=> *'(.+?)'(,|$)~",$string,$match);
$array = array_combine($match[1],$match[2]);
var_dump($array);
I added a ' to the string from the request for testing purposes.
Demo: https://3v4l.org/6YO8Q

PHP associative array values replace string variable

I have a string as:
$string = "My name is {name}. I live in {detail.country} and age is {detail.age}";
and I have an array like that and it will be always in that format.
$array = array(
'name' => 'Jon',
'detail' => array(
'country' => 'India',
'age' => '25'
)
);
and the expected output should be like :
My name is Jon. I live in India and age is 25
So far I tried with the following method:
$string = str_replace(array('{name}','{detail.country}','{detail.age}'), array($array['name'],$array['detail']['country'],$array['detail']['age']));
But the thing is we can not use the plain text of string variable. It should be dynamic on the basis of the array keys.
You can use preg_replace_callback() for a dynamic replacement:
$string = preg_replace_callback('/{([\w.]+)}/', function($matches) use ($array) {
$keys = explode('.', $matches[1]);
$replacement = '';
if (sizeof($keys) === 1) {
$replacement = $array[$keys[0]];
} else {
$replacement = $array;
foreach ($keys as $key) {
$replacement = $replacement[$key];
}
}
return $replacement;
}, $string);
It also exists preg_replace() but the above one allows matches processing.
You can use a foreach to achieve that :
foreach($array as $key=>$value)
{
if(is_array($value))
{
foreach($value as $key2=>$value2)
{
$string = str_replace("{".$key.".".$key2."}",$value2,$string);
}
}else{
$string = str_replace("{".$key."}",$value,$string);
}
}
print_r($string);
The above will only work with a depth of 2 in your array, you'll have to use recurcivity if you want something more dynamic than that.
Here's a recursive array handler: http://phpfiddle.org/main/code/e7ze-p2ap
<?php
function replaceArray($oldArray, $newArray = [], $theKey = null) {
foreach($oldArray as $key => $value) {
if(is_array($value)) {
$newArray = array_merge($newArray, replaceArray($value, $newArray, $key));
} else {
if(!is_null($theKey)) $key = $theKey . "." . $key;
$newArray["{" . $key . "}"] = $value;
}
}
return $newArray;
}
$array = [
'name' => 'Jon',
'detail' => [
'country' => 'India',
'age' => '25'
]
];
$string = "My name is {name}. I live in {detail.country} and age is {detail.age}";
$array = replaceArray($array);
echo str_replace(array_keys($array), array_values($array), $string);
?>
echo "my name is ".$array['name']." .I live in ".$array['detail']['countery']." and my age is ".$array['detail']['age'];

PHP separate number based on 2 delimiter

PHP seperate number using based on 2 delimiter
I have this variable $sid
$sid = isset($_POST['sid']) ? $_POST['sid'] : '';
and it's output is:
Array
(
[0] => 4|1
[1] => 5|2,3
)
Now I want to get the 1, 2, 3 as value so that I can run a query based on this number as ID.
How can I do this?
Use explode()
$arr = array(
0 => "4|1",
1=> "5|2,3"
);
$output = array();
foreach($arr as $a){
$right = explode("|",$a);
$rightPart = explode(",",$right[1]);
foreach($rightPart as $rp){
array_push($output,$rp);
}
}
var_dump($output);
Use foreach to loop thru your array. You can explode each string to convert it to an array. Use only the 2nd element of the array to merge
$sid = array('4|1','5|2,3');
$result = array();
foreach( $sid as $val ) {
$val = explode('|', $val, 2);
$result = array_merge( $result, explode(',', $val[1]) );
}
echo "<pre>";
print_r( $result );
echo "</pre>";
You can also use array_reduce
$sid = array('4|1','5|2,3');
$result = array_reduce($sid, function($c, $v){
$v = explode('|', $v, 2);
return array_merge($c, explode(',', $v[1]));
}, array());
These will result to:
Array
(
[0] => 1
[1] => 2
[2] => 3
)
You can do 2 explode with loop to accomplish it.
foreach($sid as $a){
$data = explode("|", $a)[1];
foreach(explode(",", $data) as $your_id){
//do you stuff with your id, for example
echo $your_id . '<br/>';
}
}

JSON arrays using PHP

I'm having an array "pollAnswers" which displays:
Array
(
[0] => Sachin
[1] => Dhoni
)
in PHP and I want it to display as:
"pollAnswers":[
{"pollAnswersID":0, "pollAnswer":"Sachin"},
{"pollAnswersID":1, "pollAnswer":"Dhoni"}
]
in JSON output.
I've tried using array_fill_keys and array_flip but that's not solution for this. It seems I need to split the array_keys and array_values and then do some concatenation to get this, but I'm stuck here!
Online check link
Try this
$arr = array("Sachin", "Dhoni");
$sub_arr = array();
$final = array();
foreach($arr as $key => $val){
$sub_arr['pollAnswersId'] = $key;
$sub_arr['pollAnswer'] = $val;
$sub_final[] = $sub_arr;
}
$final['pollAnswers'] = $sub_final;
echo json_encode($final);
result
{"pollAnswers":[
{"pollAnswersId":0,"pollAnswer":"Sachin"},
{"pollAnswersId":1,"pollAnswer":"Dhoni"}
]}
You can try with array_map.
$Array = array('Sachin', 'Dhoni');
$new = array_map(function($v, $k) {
return ['pollAnswersId' => $k, 'pollAnswer' => $v]; // return the sub-array
}, $Array, array_keys($Array)); // Pass the values & keys
var_dump(json_encode(array("pollAnswers" => $new)));
Output
"{"pollAnswers":[
{"pollAnswersId":0,"pollAnswer":"Sachin"},
{"pollAnswersId":1,"pollAnswer":"Dhoni"}
]}"
For older versions of PHP.
return array('pollAnswersId' => $k, 'pollAnswer' => $v);
Fiddle
<?php
$answerArray = [];
foreach($yourArray as $key => $r)
$answerArray[] = ['pollAnswersId' => $key, 'pollAnswer' => $r];
echo json_encode($answerArray);
Here you go.
Try this:
$givenArray = array("Sachin","Dhoni");
$answerArray = [];
foreach($givenArray as $key => $r)
$answerArray[] = ['pollAnswersId' => $key, 'pollAnswer' => $r];
echo $out = json_encode(array('pollAnswers' => $answerArray));

How to convert an array to string with index

I would like to convert an Array like this:
array ( [1_1] => 1 [1_2] => 2 [1_3] => 3 [1_4] => 4 [1_5] => 5 )
to an string like this:
"1_1-1/1_2-2/1_3-3/1_4-4/1_5-5"
how can I do it?
I need the Index and the values in my MySQL-Databse.
I tryed implode() but this is the result:
1/2/3/4/5
thank you
$out = "";
foreach($arr as $k => $v) {
$out .= "$k-$v/";
}
$out = substr($out, 0, -1); //this line will remove the extra '/'
PHP < 5.5
It's better to store all these values in an associative array and then implode them
$final = array();
foreach($array as $key => $val)
{
$final[] = $key.'-'.$val;
}
$final = implode('/', $final);
PHP = 5.5
You may want to use generators to yeld these values assuming they are regular:
See: http://php.net/manual/en/language.generators.overview.php
You can use http_build_query() to do that.
http://www.php.net/http_build_query
Try:
echo http_build_query($array, '', '/');

Categories