This question already has answers here:
sort a multi-dimensional associative array?
(3 answers)
Closed 5 years ago.
i have seen several SO answers but none seem to address this very simple situation.
my array looks like the following:
$myArray =
['person_1#gmail.com'] =>
['2017-01-05'] =>
'this is line one'
'this is line two'
['2016-05-05'] =>
'this is another line'
'and this is a fourth line'
['2017-07-10'] =>
'more lines'
'yet another line'
['person_2#gmail.com'] =>
['2015-01-01'] =>
'line for person_2'
within each of the first levels (email address), how would I sort the second level (date yyyy-mm-dd) in descending?
I did try this:
foreach ( $myArray as $emailAddress => $emailAddressArrayOfDates ) {
usort ( $myArray[$emailAddress] );
}
and I also tried to ksort with a function as well with no success.
thank you very much.
Use this:
foreach($myArray as $emailAddressKey=>$datesArray){
krsort($myArray[$emailAddressKey]);
}
print_r($myArray);
or (but i prefer the first option)
foreach($myArray as &$value){
krsort($value);
// this works only if $value is passed by reference. If it's not,
// it will update $value, but not $myArray[$key] as $value is only
// a local variable.
}
print_r($myArray);
This is the sorting method:
krsort — Sort an array by key in reverse order
bool krsort ( array &$array [, int $sort_flags = SORT_REGULAR ] )
See a working example here: https://3v4l.org/pok2e
Related
This question already has answers here:
Merge row data from multiple arrays
(6 answers)
Closed 4 months ago.
How can I combine 2 arrays ... :
$array_1 = [['title' => 'Google'], ['title' => 'Bing']];
$array_2 = [['link' => 'www.example1.com'], ['link' => 'www.example2.com']];
In order to get ... :
$array_3 = [
['title' => 'Google', 'link' => 'www.example1.com'],
['title' => 'Bing', 'link' => 'www.example2.com']
];
I guess $array_3 should be structured the following way in order to get :
Final result:
Google - See website
Bing - See website
The function to get the final result:
function site_and_link($array_3) {
foreach ($array_3 as $a) {
echo $a['title'] . " - See website</br>";
}
}
What is the missing step to arrange $array_3?
You can use a simple foreach loop and array_merge to merge both subarrays.
<?php
$result = [];
foreach($array_1 as $index => $val){
$result[] = array_merge($val,$array_2[$index]);
}
print_r($result);
It is indirect programming to use a loop to merge-transpose your array data, then another loop to print to screen.
Ideally, you should try to merge these structures earlier in your code if possible (I don't know where these datasets are coming from, so I cannot advise.)
Otherwise, leave the two arrays unmerged and just write a single loop to print to screen. Because the two arrays are expected to relate to each other by their indexes, there will be no risk of generating Notices.
Since I am typing this out, I'll take the opportunity to reveal a couple of useful tricks:
You can unpack your single-element subarrays by using array syntax with a static key pointing to the targeted variable in the foreach().
Using printf() can help to cut down on line bloat/obfuscation caused by concatenation/interpolation. By writing placeholders (%s) into the string and then passing values for those placeholders in the trailing arguments, readablity is often improved.
Code: (Demo)
$sites = [['title' => 'Google'], ['title' => 'Bing']];
$links = [['link' => 'www.example1.com'], ['link' => 'www.example2.com']];
foreach ($sites as $index => ['title' => $title]) {
printf(
'%s - See website</br>',
$title,
$links[$index]['link']
);
}
Output:
Google - See website</br>
Bing - See website</br>
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.
I work with a CMS (Drupal 8). It automatically generates some multidimensional array with an unique value, like this :
//var_dump of my $array
array (size=1)
0 =>
array (size=1)
'value' => string '50' (length=2)
To date, I use this ugly way for automatically get the value (in example : "50") of these arrays :
array_shift(array_values(array_shift(array_values($array))))
My question is, is there a better way in php for get that ?
So you know it's an array in an array?
$value = reset(reset($array));
You don't know how many turtles arrays are nested?
$value = $array;
while(is_array($value))
$value = reset($array);
Docs on reset
Just use via index:
$array[0]['value']
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:
Getting the key of the only element in a PHP array
(6 answers)
Closed 8 years ago.
How do I get the value of a key of any array item? Like how a foreach loop turns it into $k => $v...except I only want to do that once, so no need for a loop. Do I really need to make a new array that it flips to?
Take this for example.
1 => array(
'street' => 'Street Address ',
'town' => 'Town/City '
),
2 => array(
'state' => 'State '
),
Those are arrays inside a bigger array. And now I tried to do this
array_flip($thatarrayupthere[2]['state'])
What I want to receive from that is "state" because that is the key name. But I'm getting errors.
I'm not exactly sure what you wan't, but if you just want to get the key of the second array in any given array this might help.
$key = key($array[2]);
In your example above you will get "state" in your $key variable.
$key = array_keys($array[2]);
print_r($key);
ref: http://php.net/manual/en/function.array-keys.php