I checked this question and answers:
How to group a multidimensional array by a particular subarray value?
He wanted to group results by 'level'. But how would you do it to group it by 'level' first and then by 'type'?
Its pretty straight forward. Loop through $items array. Get each item's level and type and if they are not set yet, initialize them with an empty array. Then just push the "cust" value into the array.
I have given the code below.
I am assuming "$items" is an array which contains the input.
$g = [];
foreach($items as $k => $v) {
$l = $v["level"];
$t = $v["type"];
$c = $v["cust"];
if(!isset($g[$l])) {
$g[$l] = [];
}
if(!isset($g[$l][$t])) {
$g[$l][$t] = [];
}
$g[$l][$t][] = [
"cust" => $c
];
}
var_dump($g);
The output of this code would be like below:
array(3) {
[1]=>
array(1) {
["standard"]=>
array(2) {
[0]=>
array(1) {
["cust"]=>
string(6) "XT8900"
}
[1]=>
array(1) {
["cust"]=>
string(6) "XT8944"
}
}
}
[3]=>
array(1) {
["premier"]=>
array(2) {
[0]=>
array(1) {
["cust"]=>
string(6) "XT8922"
}
[1]=>
array(1) {
["cust"]=>
string(6) "XT8816"
}
}
}
[7]=>
array(1) {
["standard"]=>
array(1) {
[0]=>
array(1) {
["cust"]=>
string(6) "XT7434"
}
}
}
}
[P.S.]: You can also use sort to solve this problem easily. That's another way of solving this problem.
Related
My goal is to get specific element/value from a multidimensional array and assign them in a URL in loop. I have already tried and was able to get elements in the array but this displays all elements. I only want to get specific, like nid and field_x values.
This is my link structure: http://localhost:8080/$nid/$field_x
Expected result:
http://localhost:8080/123/one
http://localhost:8080/789/three
This is my sample var_dump result
array(1) {
[0]=>
array(38) {
["nid"]=>
array(1) {
[0]=>
array(1) {
["value"]=>
int(123)
}
}
["vid"]=>
array(1) {
[0]=>
array(1) {
["value"]=>
int(456)
}
}
["field_x"]=>
array(1) {
[0]=>
array(4) {
["target_id"]=>
string(6) "One"
}
}
["field_y"]=>
array(1) {
[0]=>
array(4) {
["target_id"]=>
string(2) "Two"
}
}
}
[1]=>
array(38) {
["nid"]=>
array(1) {
[0]=>
array(1) {
["value"]=>
int(789)
}
}
["vid"]=>
array(1) {
[0]=>
array(1) {
["value"]=>
int(321)
}
}
["field_x"]=>
array(1) {
[0]=>
array(4) {
["target_id"]=>
string(6) "Three"
}
}
["field_y"]=>
array(1) {
[0]=>
array(4) {
["target_id"]=>
string(2) "Four"
}
}
}
}
You can use a foreach() and get the data using $values['nid'][0]['value'] or $values['field_x'][0]['target_id']:
foreach ($result as $values) {
$nid = $values['nid'][0]['value'];
$field_x = $values['field_x'][0]['target_id'];
echo "http://localhost:8080/$nid/$field_x" ;
}
Will outputs:
http://localhost:8080/123/One
http://localhost:8080/789/Three
You probably want to do something else than an echo, so you can create a new array:
$urls = [];
foreach ($result as $values) {
$nid = $values['nid'][0]['value'];
$field_x = $values['field_x'][0]['target_id'];
$urls[] = "http://localhost:8080/$nid/$field_x" ;
}
print_r($urls);
I have a variable list of arrays, the list depend of user input. each time the program is called a new set of single arrays is generated.
I been searching for solutions but apparently all solution refer to array of arrays.
Originally the data are from database using:
for ($i = 0; $runrwos= mysql_fetch_assoc($run); $i++) {}
after the loop data are inserted in an array:
$data[$i] = array();
Using a foreach () {} function data are manipulated with mathematical operations to get the desired outcome.
The result will output two string of data,
$A is a numeric data
$B has alphabetic value
$explodA = explode(" ", $A);
$explodB = explode(" ", $B);
Then I combine the result
$new = array_combine($explodA, $explodB);
when I check result I with
var_dump($new);
I get the following result:
array(1) { [1204]=> string(8) "Home2017" }
array(1) { [1183]=> string(8) "Home2018" }
array(1) { [1204]=> string(4) "Stan" }
array(1) { [1204]=> string(7) "Jun2017" }
array(1) { [1173]=> string(9) "APRIL2017" }
.......................................
array(1) { [953]=> string(7) "UNE2018" }
array(1) { [1171]=> string(6) "MAY201" }
I need to sort this data as follow:
array(1) { [953]=> string(7) "UNE2018" }
array(1) { [1171]=> string(6) "MAY201" }
array(1) { [1173]=> string(9) "APRIL2017" }
array(1) { [1183]=> string(8) "Home2018" }
array(1) { [1204]=> string(8) "Home2017" }
array(1) { [1204]=> string(4) "Stan" }
array(1) { [1204]=> string(7) "Jun2017" }
Can someone direct in the right direction?
I guess the solution is simple but I cannot resolve
I need some more help regarding PHP Arrays and the issue I am having. I have an array like this: -
array(2) {
[0]=>
array(2) {
[0]=>
array(2) {
["count"]=>
string(3) "100"
["id"]=>
int(46)
}
[1]=>
array(2) {
["count"]=>
string(3) "300"
["id"]=>
int(53)
}
}
[1]=>
array(1) {
[0]=>
array(2) {
["count"]=>
string(3) "200"
["id"]=>
int(46)
}
}
}
However, I would like it to look more like this as array: -
array(2) {
[0]=>
array(2) {
["count"]=>
string(3) "300" <--- This has been added from Array 1 and 2
["id"]=>
int(46)
}
[1]=>
array(2) {
["count"]=>
string(3) "300"
["id"]=>
int(53)
}
}
Basically if the same id is in both areas I want the count number to be added to each other but if it's not then it needs to just be left alone and included in the array.
I have used a number of array functions such as array_merge and array_push but I am running out of ideas of how this could work. I have also started working on a foreach with if statements but I just got myself completely confused. I just need a second pair of eyes to look at the issue and see howe it can be done.
Thanks again everyone.
Should work with something like this:
$idToCountArray = array(); //temporary array to store id => countSum
array_walk_recursive($inputArray, function($value,$key) { //walk each array in data structure
if(isset(value['id']) && isset($value['count'])) {
//we have found an entry with id and count:
if(!isset($idToCountArray[$value['id']])) {
//first count for id => create initial count
$idToCountArray[$value['id']] = intval($value['count']);
} else {
//n'th count for id => add count to sum
$idToCountArray[$value['id']] += intval($value['count']);
}
}
});
//build final structure:
$result = array();
foreach($idToCountArray as $id => $countSum) {
$result[] = array('id' => $id, 'count' => ''.$countSum);
}
Please note that I have not testet the code and there is probably a more elegant/performant solution.
You could use something like this:
$end_array = array();
function build_end_array($item, $key){
global $end_array;
if (is_array($item)){
if( isset($item["id"])){
if(isset($end_array[$item["id"]]))
$end_array[$item["id"]] = $end_array[$item["id"]] + $item["count"]*1;
else
$end_array[$item["id"]] = $item["count"]*1;
}
else {
array_walk($item, 'build_end_array');
}
}
}
array_walk($start_array, 'build_end_array');
Here is a fiddle.
Thank you ever so much everyone. I actually worked it by doing this: -
$fullArray = array_merge($live, $archive);
$array = array();
foreach($fullArray as $key=>$value) {
$id = $value['id'];
$array[$id][] = $value['count'];
}
$result = array();
foreach($array as $key=>$value) {
$result[] = array('id' => $key, 'count' => array_sum($value));
}
return $result;
I have a PHP Loop that loops through data, i want to be able to echo all of this data alphabetically.
i currently use an array:
$output[]=array();
foreach($WHM_Servers as $whm) {
foreach($server->list_accounts() as $ret) {
$output[]= '<tr class="notfirst">
<td>'.$ret["domain"].'</td>
<td>'.$ret["user"].'</td>
<td>'.CompanyInfoLookup($result["customer"], 'company').'</td>
<td>'.$ret["startdate"].'</td>
<td>'.$ret["starttime"].'</td>
<td>'.$ret["disklimit"].'</td>
<td>'.$ret["diskused"].'</td>
</tr>';
}
}
would i be able to add a key in the array and then echo the array alphabetically from the keys
A few different ways to do this, I chose to write a user defined sort function.
$accounts = array();
$accounts[]['name'] = "Tom";
$accounts[]['name'] = "Frank";
$accounts[]['name'] = "Zed";
$accounts[]['name'] = "Aaron";
function compareNames($a, $b){
return strcmp($a['name'], $b['name']);
}
usort($accounts, "compareNames");
var_dump($accounts);
Output:
array(4) {
[0]=>
array(1) {
["name"]=>
string(5) "Aaron"
}
[1]=>
array(1) {
["name"]=>
string(5) "Frank"
}
[2]=>
array(1) {
["name"]=>
string(3) "Tom"
}
[3]=>
array(1) {
["name"]=>
string(3) "Zed"
}
}
This is a standalone example. To apply it to your example, you need to store the data: $accounts = $server->list_accounts(), sort it: usort($accounts, "compareNames");, and then pass it in to your loop: foreach($accounts as $ret) {
Absolutely doing my head in here over something that I'm sure is very simple...
I have 2 arrays.
$post_cats which are categories that any given post is in.
$ad_cats which is an array of categories in which ads are placed.
Basically, if a post has in its array of selected categories, a category that matches an item in the array of ad categories, then it must return the matching value/item.
$post_cats returns this
array(4) {
[0]=> array(1) { ["slug"]=> string(6) "energy" }
[1]=> array(1) { ["slug"]=> string(6) "global" }
[2]=> array(1) { ["slug"]=> string(8) "identify" }
[3]=> array(1) { ["slug"]=> string(5) "south" }
}
and $ad_cats returns this
array(6) {
[0]=> array(1) { ["slug"]=> string(5) "north" }
[1]=> array(1) { ["slug"]=> string(5) "south" }
[2]=> array(1) { ["slug"]=> string(4) "east" }
[3]=> array(1) { ["slug"]=> string(4) "west" }
[4]=> array(1) { ["slug"]=> string(6) "global" }
[5]=> array(1) { ["slug"]=> string(8) "fallback" }
}
The duplicated item there is "south", so in my mind the value of array_intersect($post_cats, $ad_cats); should be an array with a single item - "south", correct?
But its returning, what seems like, everything in either of the arrays... I can't for the life of me get it to work..
Using the above example, I need to return "south" to a variable.
So you are looking for items that are in both arrays? ...
What about something like this:
function find_duplicate($array1, $array2)
{
$list = array();
foreach($array1 as $value1)
{
foreach($array2 as $value2)
{
if($value1 == $value2) $list[] = $value1;
}
}
return $list;
}
The best way is to convert those arrays in arrays array_intersect can work with.
Considering:
$a; // first array
$b; // second array
then you would go with:
$a1 = array();
foreach ($a as $v) $a1[] = $v['slug'];
$b1 = array();
foreach ($b as $v) $b1[] = $v['slug'];
$c = array_intersect($a1, $b1);
PHP functions usually work with more powerful algorithms than what you may think; therefore it's a good choice to let PHP functions handle this kind of things.
This solution uses array_map to get at the values and takes the intersection of that
function mapper($a)
{
return $a['slug'];
}
$set1 = array_map('mapper', $post_cats);
$set2 = array_map('mapper', $ad_cats);
$result = array_intersect($set1, $set2);
PhpFiddle for testing.