This question already has answers here:
Return single column from a multi-dimensional array [duplicate]
(7 answers)
How to implode array indexes?
(1 answer)
Closed 3 years ago.
I have an array that I am trying to convert into two strings, one with dates and one with the data values. This is a sample array:
[$output Array below]
Array
(
[2019-03-19] => Array
(
[data_values] => 1566
)
[2019-03-18] => Array
(
[data_values] => 1542
)
[2019-03-17] => Array
(
[data_values] => 786
)
[2019-03-16] => Array
(
[data_values] => 756
)
)
A desired output would be something like:
$dates = '2019-03-19,2019-03-18,2019-03-17,2019-03-16';
$data_values = '1566,1542,786,756';
I've tried this, which will give me the data_values but I can't get the dates, I assume because its the array key?
function implode_r($g, $p) {
return is_array($p) ?
implode($g, array_map(__FUNCTION__, array_fill(0, count($p), $g), $p)) :
$p;
}
$data_values = implode_r(',', $output);
echo $data_values;
You can just use array_keys and array_column:
$dates = implode(',', array_keys($output));
$data_values = implode(',', array_column($output, 'data_values'));
Demo on 3v4l.org
This will give you the answer you expect:
<?php
// Build strings based on array
function implode_r($output) {
$dates = $data_values = "";
if(is_array($output)){
$dates=implode(',',array_keys($output));
$data_values=implode(',',array_column($output, 'data_values'));
}
return compact('dates', 'data_values');
}
// Example usage
$output = [
"2019-03-17" => ["data_values" => 1],
"2019-03-18" => ["data_values" => 2],
"2019-03-19" => ["data_values" => 3],
"2019-03-20" => ["data_values" => 4]
];
$result = implode_r($output);
echo $result['dates'];
echo $result['data_values'];
Related
This question already has answers here:
Filter/Remove rows where column value is found more than once in a multidimensional array
(4 answers)
Closed 9 months ago.
Is it possible to remove sub arrays, if the array item at position 0 of that sub array matches subsequent items?
For example;
Array ( [0] => Array ( [0] => 1234 [1] => XX000 )
[1] => Array ( [0] => 1234 [1] => XX001 )
[2] => Array ( [0] => 1234 [1] => XX002 )
)
Would be adjusted to output;
Array ( [0] => Array ( [0] => 1234 [1] => XX000 ) )
function my_array_filter($arr){
$exist = [];
return array_filter($arr, function($element){
if( ! array_key_exist($element[0], $exist)){
$exist[$element[0]] = true;
return true;
}
return false;
});
}
Maybe it is possible with some arcane usage of array functions and callback, but I prefer keeping things simple whenever possible, so I understand my own solutions years later.
So why not program it?
$ORG = [ [ 1234, 'XX000' ],
[ 1234, 'XX001' ],
[ 1234, 'XX002' ],
[19987, 'XX000'] ];
$NEW = [];
$USEDKEYS = [];
foreach ($ORG as $one){
if (in_array($one[0], $USEDKEYS)) {
// skip.
} else {
$NEW[] = $one;
$USEDKEYS[] = $one[0];
}
}
unset ($USEDKEYS, $ORG);
var_dump ($NEW);
Always the way, I've found out the solution after posting this ($query being the multi-dimensional array);
$newArr = array();
foreach ($query as $val) {
$newArr[$val[0]] = $val;
}
$query = array_values($newArr);
This question already has answers here:
Is there a function to extract a 'column' from an array in PHP?
(15 answers)
Closed 6 years ago.
I have an array that looks like this:
Array (
[0] => Array ([order_variable_key] => surname [order_variable_value] => Hudsons )
[1] => Array ( [order_variable_key] => number [order_variable_value] => 13 )
[2] => Array ( [order_variable_key] => firstname [order_variable_value] => Dave )
)
I want to convert it to an array that looks like this:
Array(
'surname' => Hudsons,
'number' => 13,
'firstname' => Dave);
I managed to isolate the values but was not able to pair them with eachother.
I want to pair the values of the nested array with eachother.
$new_array= array();
foreach($array_name1 as $key=>$val){
$new_array[$val['order_variable_key']] = $val['order_variable_value'];
}
you can use
$newArray = array();
foreach($array as $obj)
{
$newArray[$obj['order_variable_key']] = $obj['order_variable_value']
}
Try this:
$arr = // your array;
$data = array();
foreach($arr as $val)
{
$arr[$val['order_variable_key']] = $val['order_variable_value'];
}
print_r($arr);
will give your desired format.
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 this kind of array in my $tag variable.
Array
(
[0] => Array
(
[tag_name] => tag-1
)
[1] => Array
(
[tag_name] => tag-2
)
[2] => Array
(
[tag_name] => tag-3
)
)
What I'm trying to do is get all the tag names and implode them with a coma then make it a value for a text input field.
I've tried for and foreach loops so many different ways but with not much success. I'm using CodeIgniter if that helps.
You can use array_column followed by join or implode
Try this :
$string = join(',', array_column($array, 'tag_name'));
Explanation:
array_column returns the values from a single column from the input array
For your array, array_column($array 'tag_name') returns an array containing values of index tag_name, i.e returned array would be :
Array
(
[0] => tag-1
[1] => tag-2
[2] => tag-3
)
Joining with join or implode , you get your desired string,
//$string = "tag-1,tag-2,tag-3"
A simple and obvious solution might be:
$res = "";
for ($i = 0; $i < count($tag); $i++) {
$res .= $tag[$i]["tag_name"] . ",";
}
$res = trim($res, ","); //Removing the extra commas
echo $res;
You basically iterate through the array, and every element you iterate through, you add it's tag_name to a $res string.
Use array_column
$tag = implode(', ', array_column($array, 'tag_name'));
Using array_map:
$tag = implode(', ', array_map(function ($tag) {
return $tag['tag_name'];
}, $array));
Simple one liner !!
$array = [
[
"tag_name" => 'tag-1'
],
[
"tag_name" => 'tag-2'
],
[
"tag_name" => 'tag-3'
],
];
implode(',', array_column($array, 'tag_name'));
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 the following array:
Array
(
[id] => 1043847
[company] => Array
(
[businesstype] => Array
(
[0] => Array
(
[id] => 6
[name] => Business Service Provider
)
[1] => Array
(
[id] => 8
[name] => Retailer
)
)
)
)
I would like to be able to get the value of company -> businesstype -> name for all the arrays inside businesstype so it would display like this:
Business Type(s): Business Service Provider, Retailer
Right now if I do this:
<?php echo($chamber_member['company']['businesstype']['name']); ?>
Nothing happens, if I do this:
<?php echo($chamber_member['company']['businesstype'][0]['name']); ?>
I get only the one for array [0]. How can I get both values separated by a comma like on the example above? Any help is appreciated, thank you in advance!!
This should work for you:
First get the column into an array with array_column(), then you can simply implode() this array ,e.g.
echo implode(",", array_column($chamber_member["company"]["businesstype"], "name"));
foreach($chamber_member['company']['businesstype'] as $a)
$b[] = $a['name'];
$result = implode(", ", $b);
Take names by array_column and cobine by implode
<?php echo implode(',', array_column($chamber_member['company']['businesstype'], 'name')); ?>
Try to loop into the array position with the 'businesstype' values:
for($i = 0; $i < count($chamber_member['company']['businesstype']); $i++){
echo $chamber_member['company']['businesstype'][$i]['name'] . ', ';
}
I like array_column() but for completeness, just foreach():
foreach($chamber_member['company']['businesstype'] as $array) {
echo $array['name'];
}
Or add to an array and implode().
Another solution using array_map():-
$arr=array
(
'id' => 1043847,
'company' => array
(
'businesstype' => array
(
array
(
'id'=> 6 ,
'name' => 'Business Service Provider'
),
array
(
'id' => 8,
'name' => 'Retailer'
)
)
)
);
echo $names = implode(',',array_map( function($person) { return $person['name']; },$arr['company']['businesstype']));
Use this. best answer for this..
$result=$chamber_member['company']['businesstype'];
$last=end($result);
for($i=0;$i<count($result);$i++)
{
$b[$i] = $result[$i]['name']; echo $b[$i]; if($last!=$result[$i]['name']){ echo ","; }
}
This question already has answers here:
Merge two arrays as key value pairs in PHP
(3 answers)
Closed 7 years ago.
Given these two array:
$name=array("alice","ken","wendy");
$frequent=array(3,6,9);
I try to combine it like
$data = array($name=>$frequent);
but it fails. Anyone can help?
I want this:
$data = array(
'alice' => 3,
'ken' => 6,
'wendy' => 9,
);
You can use array_combine
$combined_array = array_combine($name, $frequent);
Documentation here: http://php.net/manual/en/function.array-combine.php
You can use array_combine function as
Syntax:
array_combine ( array $keys , array $values )
So yours is like
$name=array("alice","ken","wendy");
$frequent=array(3,6,9);
$result = array_combine($name,$frequent);
Output
Array
(
[alice] => 3
[ken] => 6
[wendy] => 9
)
[akshay#localhost tmp]$ cat test.php
<?php
$name=array("alice","ken","wendy");
$frequent=array(3,6,9);
// One easy way is
print_r( array_combine($name, $frequent) );
// Another lengthy way
while ( ($key = array_shift($name)) && ($value = array_shift($frequent)) )
{
$combined[$key] = $value;
}
print_r( $combined );
?>
Output
[akshay#localhost tmp]$ php test.php
Array
(
[alice] => 3
[ken] => 6
[wendy] => 9
)
Array
(
[alice] => 3
[ken] => 6
[wendy] => 9
)
write like this $combined_array = array_combine($name, $frequent);
If you want to do it manually.
<?php
$name=array("alice","ken","wendy");
$frequent=array(3,6,9);
$combined=array();
for($i=0; $i<3; $i++)
{
$combined[$name[$i]]=$frequent[$i];
}
var_dump($combined);
?>