Convert string into format array without remove coma PHP - 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

Related

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'];

Group together array elements

I have an array in PHP:-
$arr = ["BX_NAME0","BX_NAME1","BX_NAME2","BX_categoryName0","BX_categoryName1","BX_categoryName2","BHA_categories0","BHA_categories1","BHA_categories2"]
Here I want to group together elements based on same ending integer together in json like
$post_data = array(
'0' => array(
'BX_NAME0' => $item_type,
'BX_categoryName0' => $string_key,
'BHA_categories0' => $string_value
),
'1' => array(
'BX_NAME1' => $item_type,
'BX_categoryName1' => $string_key,
'BHA_categories1' => $string_value
),
);
I have Used:- filter_var($key , FILTER_SANITIZE_NUMBER_INT);
to get the integer part of the array elements but don't known how to group them further.
You can do it like below using preg_match():-
$new_array = array();
foreach ($arr as $ar){
preg_match_all('!\d+!', $ar, $matches); //get the number from string
$new_array[$matches[0][0]][$ar] = '';
}
echo "<pre/>";print_r($new_array);
Output:- https://eval.in/715548
It should be something like this:-
$arr = array("BX_NAME0","BX_NAME1","BX_NAME2","BX_categoryName0","BX_categoryName1","BX_categoryName2","BHA_categories0","BHA_categories1","BHA_categories2");
$post_data = array();
foreach($arr as $value) {
$key = filter_var($value , FILTER_SANITIZE_NUMBER_INT);
if(isset($post_data[$key]) && !is_array($post_data[$key])) {
$post_data[$key] = array();
}
$post_data[$key][] = $value;
}
print_r($post_data);
Tested and works
However, I suggest you use substr() to get the last character of the array item, for performance and stuff..
By using filter_var() method
$arr = ["BX_NAME0","BX_NAME1","BX_NAME2","BX_categoryName0","BX_categoryName1","BX_categoryName2","BHA_categories0","BHA_categories1","BHA_categories2"];
foreach($arr as $a){
$int = filter_var($a, FILTER_SANITIZE_NUMBER_INT);
$newarr[$int][$a] = '';
}
print_r($newarr);
Output:-https://eval.in/715581

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));

Convert string into single array, 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

How to explode a string into an array with the string as Keys and the value true

I have:
$string = "option1,option2,option8";
I would like an array such as
$options = array ("option1" => true, "option2" => true, "option8" => true);
I can do:
$array = explode(",", $string);
$options = array();
foreach ($array as $k => $v) {
$options[$v] = true;
}
I am wondering how to do it elegantly.
By using array_fill_keys
$options = array_fill_keys(explode(',', $string), true);
You can use array_fill_keys() function :
$string = "option1,option2,option8";
$options = array_fill_keys(explode(',',$string), true);
Example

Categories