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;
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'];
I would like to convert the array:
Array
(
[0] => Array
(
[send_to] => 9891616884
)
[1] => Array
(
[send_to] => 9891616884
)
)
to
$value = 9891616884, 9891616884
Try this:
//example array
$array = array(
array('send_to'=>3243423434),
array('send_to'=>11111111)
);
$value = implode(', ',array_column($array, 'send_to'));
echo $value; //prints "3243423434, 11111111"
You can use array_map:
$input = array(
array(
'send_to' => '9891616884'
),
array(
'send_to' => '9891616884'
)
);
echo implode(', ', array_map(function ($entry) {
return $entry['tag_name'];
}, $input));
Quite simple, try this:
// initialize and empty string
$str = '';
// Loop through each array index
foreach ($array as $arr) {
$str .= $arr["send_to"] . ", ";
}
//removes the final comma and whitespace
$str = trim($str, ", ");
I have an array called $context with this structure:
array(2) {
[0]=>
array(2) {
["name"]=>
string(6) "Foo"
["username"]=>
string(6) "Test"
}
[1]=>
array(2) {
["name"]=>
string(4) "John"
["username"]=>
string(3) "Doe"
}
}
I want convert it into this string:
string 1:
0: array(
'name' => 'Foo',
'username' => 'Test',
)
string 2:
1: array(
'name' => 'John',
'username' => 'Doe',
)
How you can see I want save the current index in the iteration and display the array content formatted as 'name' and 'username' in a single line. I already tried with this code:
$export = '';
foreach($context as $key => $value)
{
$export .= "{$key}: ";
print_r($value);
$export .= preg_replace(array(
'/=>\s+([a-zA-Z])/im',
'/array\(\s+\)/im',
'/^ |\G /m'
), array(
'=> $1',
'array()',
' '
), str_replace('array (', 'array(', var_export($value, true)));
print_r($export);
$export .= PHP_EOL;
}
return str_replace(array('\\\\', '\\\''), array('\\', '\''), rtrim($export));
but I'm looking for a more optimized solution, any suggest?
This is my code:
$context = [['name'=>'Foo','username'=>'Test'],['name'=>'John','username'=>'Doe']];
$schema = " '%s' => '%s'";
$lineBreak = PHP_EOL;
foreach( $context as $idx => $array )
{
$lines = array();
foreach( $array as $key => $val )
{
$lines[] = sprintf( $schema, $key, $val );
}
$output = "{$idx}: array({$lineBreak}".implode( ",{$lineBreak}", $lines )."{$lineBreak})";
echo $output.$lineBreak;
}
3v4l.org demo
It will works independently from the number of elements in sub-arrays
I have used classic built-in function sprintf to format each array row: see more.
You can change $lineBreak with you preferred endLine character;
In the above example, each string is printed, but (you have a return in your function, so i think inside a function), you can modify in this way:
$output = array();
foreach( $context as $idx => $array )
{
(...)
$output[] = "{$idx}: array({$lineBreak}".implode( ",{$lineBreak}", $lines )."{$lineBreak})";
}
to have an array filled with formatted string.
You can easly transform it in a function:
function contextToString( $context, $schema=Null, $lineBreak=PHP_EOL )
{
if( !$schema ) $schema = " '%s' => '%s'";
$output = array();
foreach( $context as $idx => $array )
{
$lines = array();
foreach( $array as $key => $val )
{
$lines[] = sprintf( $schema, $key, $val );
}
$output[] = "{$idx}: array({$lineBreak}".implode( ",{$lineBreak}", $lines )."{$lineBreak})";
}
return implode( $lineBreak, $output );
}
to change each time the schema and the line break.
PS: I see that in you code there is a comma also at the end of the last element of eache array; thinking it was a typo, I have omitted it
Edit: I have forgot the comma, added-it.
Edit 2: Added complete function example.
Edit 3: Added link to sprintf PHP page
Try this with personnal toString
$a = array(array("name"=>"Foo", "username"=>"Test"), array("name"=>"John", "username"=>"Doe"));
function toString($array){
$s = ""; $i=0;
foreach ($array as $key => $value) {
$s.= $key."=>".$value;
if($i < count($array)-1)
$s.=",";
$i++;
}
return $s;
}
$result = array();
$index = 0;
foreach ($a as $value) {
array_push($result, $index. " : array(" . toString($value).")");
$index ++;
}
var_dump($result);
And the result :
array (size=2)
0 => string '0 : array(name=>Foo,username=>Test)' (length=35)
1 => string '1 : array(name=>John,username=>Doe)' (length=35)
The result is in an array but you can change and make what you want
But you can also use json_encode :
$result = array();
$index = 0;
foreach ($a as $value) {
array_push($result, $index. " : array(" . json_encode($value).")");
$index ++;
}
var_dump($result);
With this result :
array (size=2)
0 => string '0 : array({"name":"Foo","username":"Test"})' (length=43)
1 => string '1 : array({"name":"John","username":"Doe"})' (length=43)
Simplified solution with strrpos,substr_replace and var_export:
$arr = [
array(
'name' => 'John',
'username' => 'Doe'
),
array(
'name' => 'Mike',
'username' => 'Tyson'
)
];
/*****************/
$strings = [];
foreach($arr as $k => $v){
$dump = var_export($v, true);
$last_comma_pos = strrpos($dump,",");
$cleared_value = substr_replace($dump, "", $last_comma_pos, 1);
$strings[] = $k.": ".$cleared_value;
}
/*****************/
// Now $strings variable contains all the needed strings
echo "<pre>";
foreach($strings as $str){
echo $str . "\n";
}
// the output:
0: array (
'name' => 'John',
'username' => 'Doe'
)
1: array (
'name' => 'Mike',
'username' => 'Tyson'
)
I have an array like:
Array
(
[0] => Array
(
[kanal] => TV3+
[image] => 3Plus-Logo-v2.png
)
[1] => Array
(
[kanal] => 6\'eren
[image] => 6-eren.png
)
[2] => Array
(
[kanal] => 5\'eren
[image] => 5-eren.png
)
)
It may expand to several more subarrays.
How can I make a list like: TV3+, 6'eren and 5'eren?
As array could potentially be to further depths, you would be best off using a recursive function such as array_walk_recursive().
$result = array();
array_walk_recursive($inputArray, function($item, $key) use (&$result) {
array_push($result, $item['kanal']);
}
To then convert to a comma separated string with 'and' separating the last two items
$lastItem = array_pop($result);
$string = implode(',', $result);
$string .= ' and ' . $lastItem;
Took some time but here we go,
$arr = array(array("kanal" => "TV3+"),array("kanal" => "5\'eren"),array("kanal" => "6\'eren"));
$arr = array_map(function($el){ return $el['kanal']; }, $arr);
$last = array_pop($arr);
echo $str = implode(', ',$arr) . " and ".$last;
DEMO.
Here you go ,
$myarray = array(
array(
'kanal' => 'TV3+',
'image' => '3Plus-Logo-v2.png'
),
array(
'kanal' => '6\'eren',
'image' => '6-eren.png'
),
array(
'kanal' => '5\'eren',
'image' => '5-eren.png'
),
);
foreach($myarray as $array){
$result_array[] = $array['kanal'];
}
$implode = implode(',',$result_array);
$keyword = preg_replace('/,([^,]*)$/', ' & \1', $implode);
echo $keyword;
if you simply pass in the given array to implode() function,you can't get even the value of the subarray.
see this example
assuming your array name $arr,codes are below
$length = sizeof ( $arr );
$out = '';
for($i = 0; $i < $length - 1; $i ++) {
$out .= $arr [$i] ['kanal'] . ', ';
}
$out .= ' and ' . $arr [$length - 1] ['kanal'];
I think it would work to you:
$data = array(
0 =>['kanal' => 'TV1+'],
1 =>['kanal' => 'TV2+'],
2 =>['kanal' => 'TV3+'],
);
$output = '';
$size = sizeof($data)-1;
for($i=0; $i<=$size; $i++) {
$output .= ($size == $i && $i>=2) ? ' and ' : '';
$output .= $data[$i]['kanal'];
$output .= ($i<$size-1) ? ', ' : '';
}
echo $output;
//if one chanel:
// TV1
//if two chanel:
// TV1 and TV2
//if three chanel:
// TV1, TV2 and TV3
//if mote than three chanel:
// TV1, TV2, TV3, ... TV(N-1) and TV(N)
$last = array_slice($array, -1);
$first = join(', ', array_slice($array, 0, -1));
$both = array_filter(array_merge(array($first), $last));
echo join(' and ', $both);
Code is "stolen" from here: Implode array with ", " and add "and " before last item
<?php
foreach($array as $arr)
{
echo ", ".$arr['kanal'];
}
?>
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