This question already has answers here:
Implode a column of values from a two dimensional array [duplicate]
(3 answers)
Closed 8 months ago.
I'm a novice at PHP and I need a quick solution to the following problem but can't seem to come up with one:
I have a multi-dimensional array like so
Array
(
[0] => Array
(
[blogTags_id] => 1
[tag_name] => google
[inserted_on] => 2013-05-22 09:51:34
[inserted_by] => 2
)
[1] => Array
(
[blogTags_id] => 2
[tag_name] => technology
[inserted_on] => 2013-05-22 09:51:34
[inserted_by] => 2
)
)
I want to use the implode() to somehow return a comma-separated string containing values of tag_name key like so.
google, technology
Is it possible to achieve this effect with the said function? If not then please suggest an alternate solution.
Quite simple:
$input = array(
array(
'tag_name' => 'google'
),
array(
'tag_name' => 'technology'
)
);
echo implode(', ', array_map(function ($entry) {
return $entry['tag_name'];
}, $input));
http://3v4l.org/ltBZ0
and new in php v5.5.0, array_column:
echo implode(', ', array_column($input, 'tag_name'));
Although this question is related to string conversion, I stumbled upon this while wanting an easy way to write arrays to my log files. If you just want the info, and don't care about the exact cleanliness of a string you might consider:
json_encode($array)
array_map is a call back function, where you can play with the passed array.
this should work.
$str = implode(',', array_map(function($el){ return $el['tag_id']; }, $arr));
join(',', array_map(function (array $tag) { return $tag['tag_name']; }, $array))
very simple go for this
$str;
foreach ($arrays as $arr) {
$str .= $arr["tag_name"] . ",";
}
$str = trim($str, ',');//removes the final comma
If you want "tag_name" with associated "blogTags_id" use: (PHP > 5.5)
$blogDatas = array_column($your_multi_dim_array, 'tag_name', 'blogTags_id');
echo implode(', ', array_map(function ($k, $v) { return "$k: $v"; }, array_keys($blogDatas), array_values($blogDatas)));
In this situation implode($array,','); will works, becasue you want the values only. In PHP 5.6 working for me.
If you want to implode the keys and the values in one like :
blogTags_id: 1
tag_name: google
$toImplode=array();
foreach($array as $key => $value) {
$toImplode[]= "$key: $value".'<br>';
}
$imploded=implode('',$toImplode);
Sorry, I understand wrong, becasue the title "Implode data from a multi-dimensional array". Well, my answer still answer it somehow, may help someone, so will not delete it.
Related
This question already has answers here:
Is there a function to extract a 'column' from an array in PHP?
(15 answers)
Closed 9 months ago.
I have this array. I want to get the array values to a same array,how can I achieve that?
Array
(
[0] => Array
(
[referrer_id] => usr157
)
[1] => Array
(
[referrer_id] => usr42
)
)
I want this array to be
array("usr157", "usr42")
use array_walk_recursive to achieve the result as follows
<?php
$main = [];
$ref =
[
[
"referrer_id" => "usr157"
],
[
"referrer_id" => "usr42"
]
];
array_walk_recursive($ref, function ($item, $key) use(&$main) {
$main[] = $item;
} );
print_r($main);
You can check that out here
You can just access the array components like this:
// The next line just recreates your example array into a variable called $x:
$x = array(array('referrer_id' => 'usr157'), array('referrer_id' => 'usr42'));
$result = array($x[0]['referrer_id'], $x[1]['referrer_id']);
print_r($result); //print the result for correctness checking
$result will be the output array you wanted.
Using $x[0], you refer the first element of your input array (and hence, $x[1] the second one, ...). Adding ['referrer_id'] will access its referrer_id key. The surrounding array(...) puts the values into an own array.
You can "automate" the whole thing in case you have a bigger input array using a loop.
You may use array_column to achieve that
$flatten = array_column($array, 'referrer_id');
You can also use array_map and array_values together.
$array = [
[
"referrer_id" => "usr157"
],
[
"referrer_id" => "usr42"
]
];
$flatten = array_map(function($item) {
return array_values($item)[0];
}, $array);
var_dump($flatten);
Also you can use the one-liner if you're using latest version of php that support arrow function
$flatten = array_map(fn($item) => array_values($item)[0], $array);
Or without array_values, you may specify the key
$flatten = array_map(fn($item) => $item['referrer_id'], $array);
You can see the demo here
This question already has answers here:
Generate an associative array from an array of rows using one column as keys and another column as values
(3 answers)
Closed 5 months ago.
The Microsoft QnAMaker API is returning a JSON key/value array (Metadata) in the following format:
$array = [[
"name" => "someName1",
"value" => "someValue1",
],
[
"name" => "someName2",
"value" => "someValue2",
],
..etc..
];
How do i transform it to be in the following more usable format:
$array = [
"someName1" => "someValue1",
"someName2" => "someValue2",
..etc..
];
I know I can do it using a loop... Is there a way to leverage on built in functions?
If a loop is the only way, how would you write it and why (performance/readibility/etc.)?
If it looks JSONish, array_column helps. Simply:
<?php
var_export(array_column($array, 'value', 'name'));
Output:
array (
'someName1' => 'someValue1',
'someName2' => 'someValue2',
)
This uses a combination of array_map() to re-map each element and then array_merge() to flatten the results...
print_r(array_merge(...array_map(function($data)
{ return [ $data['name'] => $data['value']]; }
, $array)));
It's not very elegant and would be interesting to see other ideas around this.
Which gives...
Array
(
[someName1] => someValue1
[someName2] => someValue2
)
There isn't really a way besides a loop, so just loop through the array, and create a new array the way you need it.
$new_array = [];
foreach($array as $row) {
$new_array[$row['name']] = $row['value'];
}
print_r($new_array);
There may be a few functions you can tie together to do what you want, but in general, the loop would probably be more readable and easier in overall.
As my previous answer was a dupe of GrumpyCroutons, I thought I'd rewrite with many array functions for good measure. (But don't use this, just do a simple foreach).
<?php
array_walk($array, function($v) use (&$result) {
$result[array_shift($v)] = array_values($v)[0];
});
var_export($result);
Output:
array (
'someName1' => 'someValue1',
'someName2' => 'someValue2',
)
This works:
$res = [];
array_walk($array, function(&$e) use(&$res) {
$res[$e['name']] = $e['value'];
unset($e); // this line adds side effects and it could be deleted
});
var_dump($res);
Output:
array(2) {
["someName1"]=> string(10) "someValue1"
["someName2"]=> string(10) "someValue2"
}
You can simply use array_reduce:
<?php
$output = array_reduce($array, function($a, $b) {
$a[$b['name']] = $b['value'];
return $a;
});
var_export($output);
Output:
array (
'someName1' => 'someValue1',
'someName2' => 'someValue2',
)
While getting a shift on (a non-foreach):
<?php
$c = $array;
while($d = array_shift($c))
$e[array_shift($d)] = array_shift($d);
var_export($e);
Output:
array (
'someName1' => 'someValue1',
'someName2' => 'someValue2',
)
Although it suggests in the comments in the manual that shifting is more expensive than popping. You could replace the initial assignment to $c above with an array_reverse and the while-shift with a while-pop.
However, either approach is probably lousy compared to a foreach, but here for who knows whos amusement.
This question already has answers here:
Implode a column of values from a two dimensional array [duplicate]
(3 answers)
Closed 8 months ago.
I'm a novice at PHP and I need a quick solution to the following problem but can't seem to come up with one:
I have a multi-dimensional array like so
Array
(
[0] => Array
(
[blogTags_id] => 1
[tag_name] => google
[inserted_on] => 2013-05-22 09:51:34
[inserted_by] => 2
)
[1] => Array
(
[blogTags_id] => 2
[tag_name] => technology
[inserted_on] => 2013-05-22 09:51:34
[inserted_by] => 2
)
)
I want to use the implode() to somehow return a comma-separated string containing values of tag_name key like so.
google, technology
Is it possible to achieve this effect with the said function? If not then please suggest an alternate solution.
Quite simple:
$input = array(
array(
'tag_name' => 'google'
),
array(
'tag_name' => 'technology'
)
);
echo implode(', ', array_map(function ($entry) {
return $entry['tag_name'];
}, $input));
http://3v4l.org/ltBZ0
and new in php v5.5.0, array_column:
echo implode(', ', array_column($input, 'tag_name'));
Although this question is related to string conversion, I stumbled upon this while wanting an easy way to write arrays to my log files. If you just want the info, and don't care about the exact cleanliness of a string you might consider:
json_encode($array)
array_map is a call back function, where you can play with the passed array.
this should work.
$str = implode(',', array_map(function($el){ return $el['tag_id']; }, $arr));
join(',', array_map(function (array $tag) { return $tag['tag_name']; }, $array))
very simple go for this
$str;
foreach ($arrays as $arr) {
$str .= $arr["tag_name"] . ",";
}
$str = trim($str, ',');//removes the final comma
If you want "tag_name" with associated "blogTags_id" use: (PHP > 5.5)
$blogDatas = array_column($your_multi_dim_array, 'tag_name', 'blogTags_id');
echo implode(', ', array_map(function ($k, $v) { return "$k: $v"; }, array_keys($blogDatas), array_values($blogDatas)));
In this situation implode($array,','); will works, becasue you want the values only. In PHP 5.6 working for me.
If you want to implode the keys and the values in one like :
blogTags_id: 1
tag_name: google
$toImplode=array();
foreach($array as $key => $value) {
$toImplode[]= "$key: $value".'<br>';
}
$imploded=implode('',$toImplode);
Sorry, I understand wrong, becasue the title "Implode data from a multi-dimensional array". Well, my answer still answer it somehow, may help someone, so will not delete it.
This question already has answers here:
How to get an array of specific "key" in multidimensional array without looping [duplicate]
(4 answers)
Closed 1 year ago.
I have a multidimensional array, that has say, x number of columns and y number of rows.
I want specifically all the values in the 3rd column.
The obvious way to go about doing this is to put this in a for loop like this
for(i=0;i<y-1;i++)
{
$ThirdColumn[] = $array[$i][3];
}
but there is an obvious time complexity of O(n) involved here. Is there a built in way for me to simply extract each of these rows from the array without having to loop in.
For example (this does not work offcourse)
$ThirdColumn = $array[][3]
Given a bidimensional array $channels:
$channels = array(
array(
'id' => 100,
'name' => 'Direct'
),
array(
'id' => 200,
'name' => 'Dynamic'
)
);
A nice way is using array_map:
$_currentChannels = array_map(function ($value) {
return $value['name'];
}, $channels);
and if you are a potentate (php 5.5+) through array_column:
$_currentChannels = array_column($channels, 'name');
Both results in:
Array
(
[0] => Direct
[1] => Dynamic
)
Star guests:
array_map (php4+) and array_column (php5.5+)
// array array_map ( callable $callback , array $array1 [, array $... ] )
// array array_column ( array $array , mixed $column_key [, mixed $index_key = null ] )
Is there a built in way for me to simply extract each of these rows from the array without having to loop in.
Not yet. There will be a function soon named array_column(). However the complexity will be the same, it's just a bit more optimized because it's implemented in C and inside the PHP engine.
Try this....
foreach ($array as $val)
{
$thirdCol[] = $val[2];
}
Youll endup with an array of all values from 3rd column
Another way to do the same would be something like $newArray = array_map( function($a) { return $a['desiredColumn']; }, $oldArray ); though I don't think it will make any significant (if any) improvement on the performance.
You could try this:
$array["a"][0]=10;
$array["a"][1]=20;
$array["a"][2]=30;
$array["a"][3]=40;
$array["a"][4]=50;
$array["a"][5]=60;
$array["b"][0]="xx";
$array["b"][1]="yy";
$array["b"][2]="zz";
$array["b"][3]="aa";
$array["b"][4]="vv";
$array["b"][5]="rr";
$output = array_slice($array["b"], 0, count($array["b"]));
print_r($output);
This question already has answers here:
Implode a column of values from a two dimensional array [duplicate]
(3 answers)
Closed 8 months ago.
I'm a novice at PHP and I need a quick solution to the following problem but can't seem to come up with one:
I have a multi-dimensional array like so
Array
(
[0] => Array
(
[blogTags_id] => 1
[tag_name] => google
[inserted_on] => 2013-05-22 09:51:34
[inserted_by] => 2
)
[1] => Array
(
[blogTags_id] => 2
[tag_name] => technology
[inserted_on] => 2013-05-22 09:51:34
[inserted_by] => 2
)
)
I want to use the implode() to somehow return a comma-separated string containing values of tag_name key like so.
google, technology
Is it possible to achieve this effect with the said function? If not then please suggest an alternate solution.
Quite simple:
$input = array(
array(
'tag_name' => 'google'
),
array(
'tag_name' => 'technology'
)
);
echo implode(', ', array_map(function ($entry) {
return $entry['tag_name'];
}, $input));
http://3v4l.org/ltBZ0
and new in php v5.5.0, array_column:
echo implode(', ', array_column($input, 'tag_name'));
Although this question is related to string conversion, I stumbled upon this while wanting an easy way to write arrays to my log files. If you just want the info, and don't care about the exact cleanliness of a string you might consider:
json_encode($array)
array_map is a call back function, where you can play with the passed array.
this should work.
$str = implode(',', array_map(function($el){ return $el['tag_id']; }, $arr));
join(',', array_map(function (array $tag) { return $tag['tag_name']; }, $array))
very simple go for this
$str;
foreach ($arrays as $arr) {
$str .= $arr["tag_name"] . ",";
}
$str = trim($str, ',');//removes the final comma
If you want "tag_name" with associated "blogTags_id" use: (PHP > 5.5)
$blogDatas = array_column($your_multi_dim_array, 'tag_name', 'blogTags_id');
echo implode(', ', array_map(function ($k, $v) { return "$k: $v"; }, array_keys($blogDatas), array_values($blogDatas)));
In this situation implode($array,','); will works, becasue you want the values only. In PHP 5.6 working for me.
If you want to implode the keys and the values in one like :
blogTags_id: 1
tag_name: google
$toImplode=array();
foreach($array as $key => $value) {
$toImplode[]= "$key: $value".'<br>';
}
$imploded=implode('',$toImplode);
Sorry, I understand wrong, becasue the title "Implode data from a multi-dimensional array". Well, my answer still answer it somehow, may help someone, so will not delete it.