How to convert an array to string with index - php

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, '', '/');

Related

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/>';
}
}

How to get an associative array from a string?

This is the initial string:-
NAME=Marco\nLOCATION=localhost\nSECRET=fjsdgfsjfdskffuv=\n
This is my solution although the "=" in the end of the string does not appear in the array
$env = file_get_contents(base_path() . '/.env');
// Split string on every " " and write into array
$env = preg_split('/\s+/', $env);
//create new array to push data in the foreach
$newArray = array();
foreach($env as $val){
// Split string on every "=" and write into array
$result = preg_split ('/=/', $val);
if($result[0] && $result[1])
{
$newArray[$result[0]] = $result[1];
}
}
print_r($newArray);
This is the result I get:
Array ( [Name] => Marco [LOCATION] => localhost [SECRET] => fjsdgfsjfdskffuv )
But I need :
Array ( [Name] => Marco [LOCATION] => localhost [SECRET] => fjsdgfsjfdskffuv= )
You can use the limit parameter of preg_split to make it only split the string once
http://php.net/manual/en/function.preg-split.php
you should change
$result = preg_split ('/=/', $val);
to
$result = preg_split ('/=/', $val, 2);
Hope this helps
$string = 'NAME=Marco\nLOCATION=localhost\nSECRET=fjsdgfsjfdskffuv=\n';
$strXlate = [ 'NAME=' => '"NAME":"' ,
'LOCATION=' => '","LOCATION":"',
'SECRET=' => '","SECRET":"' ,
'\n' => '' ];
$jsonified = '{'.strtr($string, $strXlate).'"}';
$array = json_decode($jsonified, true);
This is based on 1) translation using strtr(), preparing an array in json format and then using a json_decode which blows it up nicely into an array...
Same result, other approach...
You can also use parse_str to parse URL syntax-like strings to name-value pairs.
Based on your example:
$newArray = [];
$str = file_get_contents(base_path() . '/.env');
$env = explode("\n", $str);
array_walk(
$env,
function ($i) use (&$newArray) {
if (!$i) { return; }
$tmp = [];
parse_str($i, $tmp);
$newArray[] = $tmp;
}
);
var_dump($newArray);
Of course, you need to put some sanity check in the function since it can insert some strange stuff in the array like values with empty string keys, and whatnot.

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

PHP, Combining each array item to the previous ones

I am building breadcrumbs and I would like to do it from all segments from the current url.
I am getting the array that looks like this
$segments = [0 =>'users',
1 =>'index',
2 =>'all'];
I'd like to combine the array in this way :
$routes = [ 0 =>'users',
1 =>'users/index',
2 =>'users/index/all'];
I have tried using array_map
$segs = array_map(function($a){return $a."/".$a;},$segments);
but it combines the same array item twice
Any help is appreciated.
This should work for you:
Just loop through each element and take an array_slice() from the start until the current element, which you then simply can implode() with a slash.
<?php
$segments = ["users", "index", "all"];
foreach($segments as $k => $v)
$result[] = implode("/", array_slice($segments, 0, ($k+1)));
print_r($result);
?>
output:
Array
(
[0] => users
[1] => users/index
[2] => users/index/all
)
If you want to do it using array_map() same as #Rizier123's method,
$segments = ['users','index','all'];
$routes = array_map(function($v, $k) use ($segments){
return implode('/', array_slice($segments, 0, ($k+1)));
}, $segments, array_keys($segments));
Use this code to fix this issue :
$arr = array(0 =>'users', 1 =>'index', 2 =>'all');
print_r(returnPath($arr));
function returnPath($urlArr = null){
$index = 1; $sep='';
$length = count($urlArr);
foreach($urlArr as $key => $item){
if($index > 1 && $index < $length){ $sep = '/'; }
$temp .= $sep.$item;
$urlArr[$key] = $temp;
$index++;
}
return $urlArr;
}
To avoid slicing and imploding on every iteration, you can concatenate and ltrim instead.
Code: (Demo)
$segments = ["users", "index", "all"];
var_export(
array_map(
function($v) {
static $path = '';
return ltrim($path .= "/$v", '/');
},
$segments
)
);
Output:
array (
0 => 'users',
1 => 'users/index',
2 => 'users/index/all',
)

Categories