I have this array:
array (size=5)
35 => string '3' (length=1)
24 => string '6' (length=1)
72 => string '1' (length=1)
16 => string '5' (length=1)
81 => string '2' (length=1)
I want to implode id to get:
$str = '35-3|24-6|72-1|16-5|81-2';
How to get it the easy way?
Thanks.
One possibility would be like this
function mapKeyVal($k, $v) {
return $k . '-' . $v;
}
echo implode('|', array_map('mapKeyVal',
array_keys($arry),
array_values($arry)
)
);
I haven't tested this, but it should be pretty straight forward ...
foreach($array as $key=>$item){
$new_arr[] = $key."-".$item;
}
$str = implode('|', $new_arr);
You cannot can do this using implode, see #havelock's answer below, however it would be easier to use a loop or another form of iteration.
$str = "";
foreach ($array as $key => $value) {
$str .= $key . "-" . $value . "|";
}
$str = substr(0, strlen($str)-1);
Solution
You can do it cleanly by joining strings, while using eg. custom associative mapping function, which looks like that:
function array_map_associative($callback, $array){
$result = array();
foreach ($array as $key => $value){
$result[] = call_user_func($callback, $key, $value);
}
return $result;
}
Full example and test
The full solution using it could look like that:
<?php
function array_map_associative($callback, $array){
$result = array();
foreach ($array as $key => $value){
$result[] = call_user_func($callback, $key, $value);
}
return $result;
}
function callback($key, $value){
return $key . '-' . $value;
}
$data = array(
35 => '3',
24 => '6',
72 => '1',
16 => '5',
81 => '2',
);
$result = implode('|', array_map_associative('callback', $data));
var_dump($result);
and the result is:
string(24) "35-3|24-6|72-1|16-5|81-2"
which matches what you expected.
The proof is here: http://ideone.com/HPsVO6
Related
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'];
My php code is
public function getAllAttributes()
{
$this->dao->select('b_title');
$this->dao->from($this->getTable_buttonsAttr());
$result = $this->dao->get();
if( !$result ) {
return array() ;
}
return $result->result();
}
$details = Modelbuttons::newInstance()->getAllAttributes();
$string = implode(', ', $details);
var_dump ($string) ; ?>
I get this an array that looks like this:
array (size=6)
0 =>
array (size=1)
'b_title' => string 'test 10' (length=12)
1 =>
array (size=1)
'b_title' => string 'test 11' (length=12)
2 =>
array (size=1)
'b_title' => string 'test 12' (length=13)
3 =>
array (size=1)
'b_title' => string 'test 13' (length=8)
4 =>
array (size=1)
'b_title' => string 'test 14' (length=14)
5 =>
array (size=1)
'b_title' => string 'test 15' (length=32)
How can I transform this array to a string like this with PHP?
$out = '10, 11, 12, 13, 14,15';
You can try this code.
$array = [['b_title' => 'test 10'],['b_title' => 'test 11']];
foreach($array as $a) {
$values[] = explode(' ', $a['b_title'])[1];
}
echo implode(', ', $values);
Basic Example:
<?php
// your array
$array = array(
array('b_title'=>'test 10'),
array('b_title'=>'test 11'),
array('b_title'=>'test 12'),
array('b_title'=>'test 13')
);
$newArr = array();
foreach ($array as $key => $value) {
$newVal = explode(" ", $value['b_title']);
$newArr[] = $newVal[1];
}
echo implode(',', $newArr); // 10,11,12,13
?>
Explanation:
First of all use explode() for your string value which help you to Split a string as required:
$newVal = explode(" ", $value['b_title']);
Than you can store index 1 in an array as:
$newArr[] = $newVal[1]; // array(10,11,12,13)
In last, you just need to use implode() function which help you to get comma separated data.
echo implode(',', $newArr); // 10,11,12,13
An alternative way to do.
$details = Modelbuttons::newInstance()->getAllAttributes(); /*[['b_title' => 'test 10'],['b_title' => 'test 11']];*/
$token = "";
foreach($details as $row1){
$token = $token.$row1['b_title'].", ";
}
echo rtrim(trim($token),",");
Output: test 10, test 11
Explanation
Through foreach, all array values are now comma separated.
As of now, output will be test 10, test 11,. So, remove extra comma which trail in the end through rtrim().
There are many ways to skin this cat -- Here's one:
<?php
$out = '';
foreach ($array as $arrayItem) {
$out .= $arrayItem['b_title'] . ', ';
}
// Remove the extraneous ", " from the $out string.
$out = substr($out, 0, -2);
?>
Or if you were also wanting to remove the "test " portion of the 'b_title' key's value; then you could accomplish it like so:
<?php
$out = '';
foreach ($array as $arrayItem) {
$out .= str_replace('test ', '', $arrayItem['b_title']) . ', ';
}
// Remove the extraneous ", " from the $out string.
$out = substr($out, 0, -2);
?>
// Construct a new array of the stripped numbers
$flattenedArray = array_map(function($item) {
list(, $number) = explode(' ', $item['b_title']);
return $number;
}, $yourArray);
// Concatenate the numbers into a string joined by ,
$out = implode(', ', $flattenedArray);
This gives the result you want. It could do with a few conditions in there though to check arrays are in the correct format before manipulation etc.
You can try this also
$check = array(array ('b_title' => array('test 10'))
,array('b_title' => array('test 11'))
,array('b_title' => array('test 12'))
,array('b_title' => array('test 13'))
,array('b_title' => array('test 14'))
,array('b_title' => array('test 15')));
$srt = "";
foreach($check as $kye => $val)
{
$title = $val['b_title'][0];
$var = explode(' ',$title);
$srt .= trim($var[1]).', ';
}
$srt = substr(trim($srt),0,-1);
$test_array = array(
0 => array('b_title' => 'test 10'),
1 => array('b_title' => 'test 11'),
2 => array('b_title' => 'test 12'),
3 => array('b_title' => 'test 13'),
4 => array('b_title' => 'test 14'),
5 => array('b_title' => 'test 15'),
);
$result = "";
$result1 = array_walk($test_array, function ($value, $key) use(&$result) {
$result .= ",".array_pop(explode(" ", reset($value))).",";
$result = trim($result, ",");
});
Output: $out = '10, 11, 12, 13, 14,15';
Explanation
Iterate over array by using PHP's native array_walk() which will reduce forloops and then prepare array by using explode(),array_pop() and trim() which is likely required to prepare your required string.
Try this,
foreach($test_array as $val)
{
$new_array[] = preg_replace('/\D/', '', $val['b_title']);
}
$out = implode(',', $new_array);
echo $out;
OUTPUT
10,11,12,13,14,15
DEMO
You can use on mentioned URL solution Click here
foreach ($arr as $k=>$val) {
$v = explode (' ', $val['b_title']);
$out .= $v[1].',';
}
$out = rtrim ($out, ',');
echo '<pre>'; print_r($out); die;
I am trying to convert a multidimensional array into a string.
Till now I have been able to convert a pipe delimited string into an array.
Such as:
group|key|value
group|key_second|value
Will render into the following array:
$x = array(
'group' => array(
'key' => 'value',
'key_second' => 'value'
),
);
However, now I want it to be the other way around, where a multidimensional array is provided and I want to convert it to a pipe delimited string just like in the first code example.
Any ideas how to do this ?
PS: Please do note that the array can dynamically have any depth.
For example:
$x['group']['sub_group']['category']['key'] = 'value'
Translates to
group|sub_group|category|key|value
I have created my own function:
This should have no problem handling even big arrays
function array_to_pipe($array, $delimeter = '|', $parents = array(), $recursive = false)
{
$result = '';
foreach ($array as $key => $value) {
$group = $parents;
array_push($group, $key);
// check if value is an array
if (is_array($value)) {
if ($merge = array_to_pipe($value, $delimeter, $group, true)) {
$result = $result . $merge;
}
continue;
}
// check if parent is defined
if (!empty($parents)) {
$result = $result . PHP_EOL . implode($delimeter, $group) . $delimeter . $value;
continue;
}
$result = $result . PHP_EOL . $key . $delimeter . $value;
}
// somehow the function outputs a new line at the beginning, we fix that
// by removing the first new line character
if (!$recursive) {
$result = substr($result, 1);
}
return $result;
}
Demo provided here http://ideone.com/j6nThF
You can also do this using a loop like this:
$x = array(
'group' => array(
'key' => 'value',
'key_second' => 'value'
)
);
$yourstring ="";
foreach ($x as $key => $value)
{
foreach ($x[$key] as $key2 => $value2)
{
$yourstring .= $key.'|'.$key2.'|'.$x[$key][$key2]."<BR />";
}
}
echo $yourstring;
Here is a working DEMO
This code should do the thing.
You needed a recursive function to do this. But be careful not to pass object or a huge array into it, as this method is very memory consuming.
function reconvert($array,$del,$path=array()){
$string="";
foreach($array as $key=>$val){
if(is_string($val) || is_numeric($val)){
$string.=implode($del,$path).$del.$key.$del.$val."\n";
} else if(is_bool($val)){
$string.=implode($del,$path).$del.$key.$del.($val?"True":"False")."\n";
} else if(is_null($val)){
$string.=implode($del,$path).$del.$key.$del."NULL\n";
}else if(is_array($val)=='array') {
$path[]=$key;
$string.=reconvert($val,$del,$path);
array_pop($path);
} else {
throw new Exception($key." has type ".gettype($val).' which is not a printable value.');
}
}
return $string;
}
DEMO: http://ideone.com/89yLLo
You can do it by
Look at serialize and unserialize.
Look at json_encode and json_decode
Look at implode
And Possible duplicate of Multidimensional Array to String
You can do this if you specifically want a string :
$x = array(
'group' => array(
'key' => 'value',
'key_second' => 'value'
),
'group2' => array(
'key2' => 'value',
'key_second2' => 'value'
),
);
$str='';
foreach ($x as $key=>$value)
{
if($str=='')
$str.=$key;
else
$str.="|$key";
foreach ($value as $key1=>$value1)
$str.="|$key1|$value1";
}
echo $str; //it will print group|key|value|key_second|value|group2|key2|value|key_second2|value
Hi i am using CakePHP version 2.x
I am print my array using
pr($this->request->params['named']);
//Output
Array
(
[street_name] => Bhubaneswar
[house_number] => 1247
[phone] => xxxxxxxx
[zip] => xxxxx
)
In above array i want to view looks like
/street_name:Bhubaneswar/house_number:1247/phone:xxxxxxxx/zip:xxxxx
How to convert above array in string format?
Try this:
$strResult = "";
foreach ($this->request->params['named'] as $key=>$value){
$strResult .= "/{$key}:{$value}";
}
The most easy and speedy solution.
$result = '';
foreach ($this->request->params['name'] as $k => $v) {
$result .= sprintf('/%s:%s', $k, $v);
}
As a one-liner:
echo '/' . str_replace('=', ':', http_build_query($array, '', '/'));
Would output:
/street_name:Bhubaneswar/house_number:1247/phone:xxx/zip:xxx
foreach (array_expression as $key => $value){
echo "/". $key . ":" . $value;
}
Try following code:
$ar = array('street_name' => 'Bhubaneswar',
'house_number' => 1247,
'phone' => 'xxxxxxxx',
'zip' => 'xxxxx');
echo convert($ar);
function convert($ar)
{
$str = '';
foreach($ar as $i=>$k)
{
$str .= '/'.$i.':'.$k;
}
return $str;
}
Output
/street_name:Bhubaneswar/house_number:1247/phone:xxxxxxxx/zip:xxxxx
function implode_with_keys($glue, $separator, $pieces)
{
$string = '';
foreach ($pieces as $key => $value) {
$string .= $glue . $key . $separator . $value;
}
return $string;
}
In your case you'd use it like this:
implode_with_keys('/', ':', $this->request->params['named']);
This will return the desired string /street_name:Bhubaneswar/house_number:1247/phone:xxxxxxxx/zip:xxxxx.
<?php
$array = array(
'street_name' => 'Bhubaneswar',
'house_number' => '1247',
'phone' => 'xxxxxxxx',
'zip' => 'xxxxx',
);
while (current($array)) {
echo '/'.key($array).':'.$array[key($array)];
next($array);
}
?>
this will return
/street_name:Bhubaneswar/house_number:1247/phone:xxxxxxxx/zip:xxxxx
$data = Array ( ['key1'] => 1 , ['key2'] => 20 , ['key3'] => 11)
$key1 = Array (1 => "a" , 2 => "b")
$key2 = Array (1 => "a" , .... 20 => "y")
$key3 = Array (1 => "a" , .... 11 => "n")
what is the easiest way to replace all values in $data array to return:
$data['key1'] = $key1[$data['key1']]
instead of doing that one by one i.e:
$data['key1'] = $key1[$data['key1']]
$data['key2'] = $key2[$data['key2']]...
I think you are looking for this:
foreach($data as $k => &$v)
{
if($$k)
{
$t = $$k;
if($t[$v]) $v = $t[$v];
}
}
print_r($data);
but I'd suggest asking yourself some bigger questions about the intent here
The question is quite hard to understand, but I think what you're trying to do is use $data to pull data from the other arrays. If that's the case, this should work:
$data = array('key1' => 1, 'key2' => 2, 'key3' => 0);
$key1 = array(1,2,3,4,5);
$key2 = array(6,7,8,9,10);
$key3 = array(11,12,13,14);
foreach(array_keys($data) as $key) {
if(isset($$key)) {
$target = $$key;
$value = $target[$data[$key]];
$data[$key] = $value;
}
}
var_dump($data); #=> [key1 => 2, key2 => 8, key3 => 11]
i'd prefer this solution
array_walk(
$data,
function(&$a, $b) {
$a = $$a[$b];
}
);
You could try using PHP's variables variables, something like this:
foreach ($data as $mkey => $mval)
{
$data[$mkey] = $$mkey[$data[$mkey]];
}