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'];
}
?>
Related
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/>';
}
}
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 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'
)
After hours going around in circles I gave up and ask for help.
I have an array which looks like:
[field01] => Array
(
[name] => test01
[prefix] => C01
)
[field02] => Array
(
[url] => http://www.url.com
[user] => a_user
[password] => a_password
)
[filed03] => Array
(
[0] => Array
(
[id] => 1
[Type] => standard
[Name] => name
)
[1] => Array
(
[id] => 5
[Type] => standard
[Name] => name
)
)
Now I want to go through that array and get the following output as a return from a recursive function:
Array (
[0] = "The values of field01: name, prefix - test01, C01"
[1] = "The values of field02: url, user, password - http://www.url.com, a_user, a_password"
[2] = "The values of field03: id, Type, Name - 1, standard, name"
[3] = "The values of field03: id, Type, Name - 5, standard, name"
)
I have tried it with a recursive function but stuck with field03 to save the name.
Any help for that?
UPDTAE:
here is the array, so you don't have to write it:
$data['field01']['name'] = "field01";
$data['field01']['prefix'] = "C01";
$data['field02']['url'] = "http://www.url.com";
$data['field02']['user'] = "a_user";
$data['field02']['password'] = "a_password";
$data['field03'][0]['List_id'] = 1;
$data['field03'][0]['Type'] = "standard";
$data['field03'][0]['Name'] = "name";
$data['field03'][1]['List_id'] = 5;
$data['field03'][1]['Type'] = "standard";
$data['field03'][1]['Name'] = "name";
Thanks in advance!
<?php
$data['field01']['name'] = "field01";
$data['field01']['prefix'] = "C01";
$data['field02']['url'] = "http://www.url.com";
$data['field02']['user'] = "a_user";
$data['field02']['password'] = "a_password";
$data['field03'][0]['List_id'] = 1;
$data['field03'][0]['Type'] = "standard";
$data['field03'][0]['Name'] = "name";
$data['field03'][1]['List_id'] = 5;
$data['field03'][1]['Type'] = "standard";
$data['field03'][1]['Name'] = "name";
$text = '';
foreach ($data as $k => $fields) {
if (isset($fields[0])) {
foreach ($fields as $field) {
$text .= 'The values of ' . $k . ': ' . traverse($field) . "\n";
}
} else {
$text .= 'The values of ' . $k . ': ' . traverse($fields) . "\n";
}
}
echo $text;
function traverse($fields) {
$keys = array_keys($fields);
$values = array_values($fields);
return implode(', ', $keys) . ' - ' . implode(', ', $values);
}
?>
This assumes if there is an array of arrays, it is all arrays. In other words, you aren't mixing strings with arrays.
$resultArray = array();
function process($inputArray, $fieldName) {
$result = array();
$keys = array_keys($inputArray);
if (!is_array($inputArray[0])) {
$result[] = "The value of $fieldName: ".implode($keys,', '). ' - '. implode($inputArray, ', ');
} else {
foreach($inputArray as $arr) {
$result = array_merge($result, process($arr, $fieldName));
}
}
return $result;
}
foreach($data as $k=>$v) {
$processed = process($v, $k);
$resultArray = array_merge($resultArray, $processed);
}
print_r($resultArray);