implode first element in associative array [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 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),',');

Related

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

Better way than array_combine to rename keys in PHP? [duplicate]

This question already has answers here:
Fastest way to add prefix to array keys?
(10 answers)
Closed 7 months ago.
I'm working off the following combination of array_combine and array_map - ideally I'd like something more like an array_map_keys to map a function to rename keys. An example:
$input = array(
'a'=>1
'b'=>2
);
$desired_output = array(
'prefix.a'=>1
'prefix.b'=>2
);
function rename_keys($input) {
array_combine(
array_map(
function($col) {
return 'prefix.'.$col;
},
array_keys($input)
),
array_values($input)
);
array_combine isn't necessary. A simple foreach should be enough.
$old = array(
'a'=>1,
'b'=>2
);
$new = array();
foreach ($old as $key => $value) {
$new['prefix.' . $key] = $value;
}
var_dump($new);
output:
array(2) {
["prefix.a"]=>
int(1)
["prefix.b"]=>
int(2)
}
edit;
Your question has already been answered here, including benchmarks for different approches
You just need to for loop it with $key and $value
$a = array('a'=>1,'b'=>2);
echo'<pre>';print_r($a);
$b=array();
foreach($a as $key => $value){
$b['prefix.'.$key] = $value;
}
echo'<pre>';print_r($b);die;
Output:
$a:
Array
(
[a] => 1
[b] => 2
)
$b :
Array
(
[prefix.a] => 1
[prefix.b] => 2
)

multidimensional array value as implode value [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 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

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));

PHP array. Simple split based on key [duplicate]

This question already has answers here:
Is there a function to extract a 'column' from an array in PHP?
(15 answers)
Closed 5 months ago.
This is more a request for a quick piece of advice as, I find it very hard to believe there isn't a native function for the task at hand. Consider the following:
array =>
(0) => array("id" => "1", "groupname" => "fudge", "etc" => "lorem ipsum"),
(1) => array("id" => "2", "groupname" => "toffee", "etc" => "lorem ipsum"),
(2) => array("id" => "3", "groupname" => "caramel", "etc" => "lorem ipsum")
)
What I am looking to get is a new array which uses only "groupname" so would equal:
array =>
(0) => "fudge",
(1) => "toffee",
(2) => "caramel"
)
I know this is very simple to achieve recursively going through the original array, but I was wondering if there is a much simpler way to achieve the end result. I've looked around the internet and on the PHP manual and can't find anything
Thank you kindly for reading this question
Simon
There is a native array_column() function exactly for this (since PHP 5.5):
$column = array_column($arr, 'groupname');
If you are using PHP 5.3, you can use array_map [docs] like this:
$newArray = array_map(function($value) {
return $value['groupname'];
}, $array);
Otherwise create a normal function an pass its name (see the documentation).
Another solution is to just iterate over the array:
$newArray = array();
foreach($array as $value) {
$newArray[] = $value['groupname'];
}
You definitely don't have to use recursion.
Use array_map:
<?php
$a = array(
array("id" => "1", "groupname" => "fudge", "etc" => "lorem ipsum"),
array("id" => "2", "groupname" => "toffee", "etc" => "lorem ipsum"),
array("id" => "3", "groupname" => "caramel", "etc" => "lorem ipsum")
);
function get_groupname( $arr )
{
return $arr['groupname'];
}
$b = array_map( 'get_groupname', $a );
var_dump( $a );
var_dump( $b );
http://codepad.org/7kNi8nNm
Values by all array keys:
$array = [
["id"=>"1","user"=>"Ivan"],
["id"=>"2","user"=>"Ivan"],
["id"=>"3","user"=>"Elena"]
];
$res = [];
$array_separate = function($value, $key) use (&$res){
foreach($value AS $k=>$v) {
$res[$k][] = $v;
}
};
array_walk($array, $array_separate);
print_r($res);
result:
Array
(
[id] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[user] => Array
(
[0] => Ivan
[1] => Ivan
[2] => Elena
)
)
http://sandbox.onlinephpfunctions.com/code/3a8f443283836468d8dc232ae8cc8d11827a5355
As far as I know there isn't a simple function in PHP that could handle this for you, the array structure is user-defined, you would have to loop through the array. The easiest way I can think of would be something like this:
for($i = 0;$i < count($main_array);$i++){
$groupname_array[] = $main_array[$i]["groupname"];
}
function array_get_keys(&$array, $key) {
foreach($array as &$value) $value = $value[$key];
}
array_get_keys($array, 'groupname');
or
function array_get_keys(&$array, $key) {
$result = Array();
foreach($array as &$value) $result[] = $value[$key];
return $result;
}
$new_array = array_get_keys($array, 'groupname');

Categories