multidimensional array value as implode value [duplicate] - php

This question already has answers here:
Implode a column of values from a two dimensional array [duplicate]
(3 answers)
Closed 7 months ago.
I am facing some problem to fix this issue. My array same as below
Array ( [0] => Array ( [coupon] => dasd ) [1] => Array ( [coupon] => aaa ) )
From here I want to display only coupon value as comma separated. Same as below
dasd,aaa
To solve this I tried below code but that's not solving my issue.
<?php
$option_settings = array(
array( 'coupon'=>'dasd'
),
array( 'coupon'=>'aaa')
);
print_r($option_settings );
echo $output = implode(',', $option_settings);
?>
Sample https://eval.in/784206

Try this code
<?php
$option_settings = array(
array( 'coupon'=>'dasd'
),
array( 'coupon'=>'aaa')
);
$arr = array();
foreach($option_settings as $opt) {
$arr[] = $opt['coupon'];
}
echo $output = implode(',', $arr);
?>
Or You can use php function array_column()
$coupans_arr =array_column($option_settings, 'coupon');
echo $output = implode(",", $coupans_arr);
Live Demo

use simple array_column method
$option_settings = array(
array( 'coupon'=>'dasd'
),
array( 'coupon'=>'aaa')
);
print_r($option_settings );
$coupans_arr =array_column($option_settings, 'coupon');
echo $output = implode(",", $coupans_arr);
https://eval.in/784217

This is what you want,
print_r(implode(',', array_column($array, 'coupon')));

Please let me know if this works:
$option_settings = array(
array( 'coupon'=>'dasd'
),
array( 'coupon'=>'aaa')
);
$result = '';
foreach($option_settings as $item)
{
$result .= $item['coupon'] .', ';
}
$result = rtrim($result, ', ');
https://eval.in/784220

Related

Change array style in PHP [duplicate]

This question already has answers here:
PHP Append an array to a sub array
(2 answers)
Closed 6 months ago.
i've been trying to make this array
$data = array (
'country' => '+57',
'message' => 'test',
'messageFormat' => 0,
'addresseeList' =>
array (
0 =>
array (
'mobile' => '1111',
'correlationLabel' => 'corelation ejemplo',
),
)
);
into this
$data = array();
$data['country'] = '+57';
$data['message'] = 'test';
$data['messageFormat'] = 0;
$data['addresseeList'] = array(
$data['mobile'] = '1111',
$data['correlationLabel'] = 'corelation ejemplo'
);
But when i try to convert this array into a json object i'm getting this
string(154) "{"country":"+57","message":"test","messageFormat":0,"mobile":"1111","correlationLabel":"corelation ejemplo","addresseeList":["1111","corelation ejemplo"]}"
but i should get something like this
string(128) "{"country":"+57","message":"test","messageFormat":0,"addresseeList":[{"mobile":"1111","correlationLabel":"corelation ejemplo"}]}"
Thanks in advance
The way you are inserting the address info actually places the mobile and correlationLabel at the root of the $data array.
instead, you need to add create an entirely new array to place as the only element inside an array you create at $data['addresseeList'].
$data = array();
$data['country'] = '+57';
$data['message'] = 'test';
$data['messageFormat'] = 0;
$data['addresseeList'][] = array(
'mobile' => '1111',
'correlationLabel' => 'corelation ejemplo'
);
echo json_encode($data, JSON_PRETTY_PRINT).PHP_EOL;

Echo Array Values in Comma Separated List [duplicate]

This question already has answers here:
Implode a column of values from a two dimensional array [duplicate]
(3 answers)
Closed 7 months ago.
I am selecting values from my database, when I dump the $results I get;
array (
0 =>
(object) array(
'FieldName' => 'certification_name',
'FieldValue' => 'White Belt',
),
1 =>
(object) array(
'FieldName' => 'certification_name',
'FieldValue' => 'Yellow Belt',
),
)
I want to display the following on my page;
Certification List: White Belt, Yellow Belt
I have created a loop but when I echo the result I get this;
Certification List: Array Array
My PHP code;
foreach ($results as $result) {
$name = $result->FieldName;
$value = $result->FieldValue;
$items[] = array(
'name' => $name,
'value' => $value
);
}
$items = implode("\n", $items);
echo 'Certification List: ' .$items;
What do I need to change in order to get this working?
You shouldn't push arrays into $items, just push the values.
foreach ($results as $result) {
$items[] = $result->FieldValue;
}
$item_list = implode(", ", $items);
echo "Certification List: $item_list";
You can also replace the loop with:
$items = array_column($results, 'FieldValue');

How to join string after last array value? [duplicate]

This question already has answers here:
How add a link on comma separated multidimensional array
(2 answers)
Closed 7 months ago.
I am trying to generate a string from an array. Need to concatenate the array values with a small string AFTER the value. It doesn't work for the last value.
$data = array (
1 => array (
'symbol' => 'salad'
),
2 => array (
'symbol' => 'wine'
),
3 => array (
'symbol' => 'beer'
)
);
$symbols = array_column($data, 'symbol');
$string_from_array = join($symbols, 'bar');
echo($string_from_array);
// expected output: saladbar, winebar, beerbar
// output: saladbar, winebar, beer
You can achieve it a few different ways. One is actually by using implode(). If there is at least one element, we can just implode by the delimiter "bar, " and append a bar after. We do the check for count() to prevent printing bar if there are no results in the $symbols array.
$symbols = array_column($data, "symbol");
if (count($symbols)) {
echo implode("bar, ", $symbols)."bar";
}
Live demo at https://3v4l.org/ms5Ot
You can also achieve the desired result using array_map(), as follows:
<?php
$data = [
1 => ['symbol' => 'salad'],
2 => ['symbol' => 'wine'],
3 => ['symbol' => 'beer']
];
echo join(", ", array_map(
fn($v) => "{$v}bar",
array_column($data, 'symbol')
)
);
See live code
Array_map() takes every element of the array resulting from array_column() pulling out the values from $data and with an arrow function, appends the string "bar". Then the new array yielded by array_map has the values of its elements joined with ", " to form the expected output which is then displayed.
As a recent comment indicated you could eliminate array_column() and instead write code as follows:
<?php
$data = [
1 => ['symbol' => 'salad'],
2 => ['symbol' => 'wine'],
3 => ['symbol' => 'beer']
];
echo join(", ", array_map(
fn($row) => "{$row['symbol']}bar",
$data
)
);
See live code
Note while this 2nd way, may appear more direct, is it? The fact is that as array_map iterates over $data, the arrow function contains code that requires dereferencing behind the scenes, namely "$row['symbol']".
The join() function is an alias of implode() which
Returns a string containing a string representation of all the array
elements in the same order, with the glue string between each element.
So you need to add the last one by yourself
$data = array (
1 => array (
'symbol' => 'salad'
),
2 => array (
'symbol' => 'wine'
),
3 => array (
'symbol' => 'beer'
)
);
$symbols = array_column($data, 'symbol');
$string_from_array = join($symbols, 'bar');
if(strlen($string_from_array)>0)
$string_from_array .= "bar";
echo($string_from_array);
You can use array_column and implode
$data = array (
1 => array (
'symbol' => 'salad'
),
2 => array (
'symbol' => 'wine'
),
3 => array (
'symbol' => 'beer'
)
);
$res = implode("bar,", array_column($data, 'symbol'))."bar";
Live Demo
Try this:
$symbols = array_column($data, 'symbol');
foreach ($symbols as $symbol) {
$symbol = $symbol."bar";
echo $symbol;
}
btw, you can't expect implode to do what you expect, because it places "bar" between the strings, and there is no between after the last string you get from your array. ;)
Another way could be using a for loop:
$res = "";
$count = count($data);
for($i = 1; $i <= $count; $i++) {
$res .= $data[$i]["symbol"] . "bar" . ($i !== $count ? ", " : "");
}
echo $res; //saladbar, winebar, beerbar
Php demo

implode first element in associative array [duplicate]

This question already has answers here:
Implode a column of values from a two dimensional array [duplicate]
(3 answers)
Closed 7 months ago.
I have one index array which contain associative array. Like this
$arr = array(
array("id" => 1,"name" => "student1"),
array("id" => 2,"name" => "student2"),
array("id" => 3,"name" => "student3"),
);
Now I want output like this
1,2,3 // output
I have solution for it but I am searching for better way to do that. Here it is
$ids = "";
for($i=0;$i<count($arr);$i++)
{
$ids .= $arr[$i]['id'].",";
}
$ids = rtrim($ids,",");
echo $ids; // output : 1,2,3
Is there any better way to achieve it?
Thanks in advance
Alternative using array_map() if you don't have PHP 5.5+:
echo implode(',', array_map(function($v) { return $v['id']; }, $arr));
Demo
If you have php version >= 5.5 then try,
echo implode(",",array_column($arr,'id'));
try this code
<?php
$arr = array(
array("id" => 1,"name" => "student1"),
array("id" => 2,"name" => "student2"),
array("id" => 3,"name" => "student3"),
);
$str = "";
foreach ($arr as $value)
{
$str=$str.$value["id"].",";
}
$str = substr($str, 0, -1);
echo $str;
?>
foreach ($arr as $val){
$ids[]=$val['id'];
}
echo implode(($ids),',');

How to parse a string into a multidimensional array when the separator is optional

I have a string ($c) that contains a comma-separated list of settings. Some settings are stand-alone, while others require a sub-setting that is separated by an equal sign.
Example:
$c = "title,author,tax=taxonomy_A,tax=taxonomy_B,date";
I need to parse this string into a multidimensional array ($columns) that outputs like this:
$columns = array(
[0] => array( 'title', '' ),
[1] => array( 'author', '' ),
[2] => array( 'tax', 'taxonomy_A' ),
[3] => array( 'tax', 'taxonomy_B' ),
[4] => array( 'date', '' )
)
I have tried this:
$c = "title,author,tax=taxonomy_A,tax=taxonomy_B,meta=custom_field_key";
$c = explode( ',', $c );
$columns = array( explode( '=', $c ) );
But that just returns this:
$columns = array(
[0] => array( 'Array' )
)
What am I missing here? Should the second explode be replaced with a different function?
Thanks in advance!
foreach(explode(',', "title,author,tax=taxonomy_A,tax=taxonomy_B,date") as $item)
$items[] = array_pad(explode('=', $item), 2, '');
You'll need to loop after the first explode to do the second one:
$c = "title,author,tax=taxonomy_A,tax=taxonomy_B,meta=custom_field_key";
$arr = explode( ',', $c );
$result = array();
foreach($arr as $a) {
array_push($result, explode('=', $a));
}
print_r($result);
In your code, you don't apply the second explode to each element of the array, but just once to the whole array object. This causes the array to be transformed into the string "Array", which is then run through explode() and results in your output.
Instead you could use array_map() (PHP docu):
function filterArr( $value ) {
return explode( '=', $value )
}
$c = "title,author,tax=taxonomy_A,tax=taxonomy_B,meta=custom_field_key";
$c = explode( ',', $c );
$c = array_map( "filterArr", $c );

Categories