PHP duplicates in nested multidimensional array to combine certain value - php

The desired output is to have:
{"userId":1,"email":"example#email.com","first":"Tyler","last":"Kanz","groups":[{"groupId":"1","groupName":"GROUP A","groupRoles":["1", "3"]},{"groupId":"2","groupName":"GROUP B","groupRoles":["2"]}]}
Which would compare the Group IDs and combine duplicates with their Group Roles.
I have tried using,
foreach ($groups as $group) {
if ($group['groupId'] == $group_id) {
array_push($group['groupRoles'], $group_role);
//And then unsetting the array
}
It is just adding all of the Groups/Roles into the Group array onto the Groups Array.
array(3) { ["groupId"]=> string(1) "1" ["groupName"]=> string(5)
"GROUP A" ["groupRoles"]=> array(1) { [0]=> string(1) "1" } } array(3) {
["groupId"]=> string(1) "2" ["groupName"]=> string(10) "GROUP B"
["groupRoles"]=> array(1) { [0]=> string(1) "2" } } array(3) {
["groupId"]=> string(1) "1" ["groupName"]=> string(5) "GROUP A"
["groupRoles"]=> array(1) { [0]=> string(1) "3" } }
{"userId":1,"email":"example#email.com","first":"Tyler","last":"Kanz","groups":[{"groupId":"1","groupName":"IRISS","groupRoles":["1"]},{"groupId":"2","groupName":"GROUP B","groupRoles":["2"]},{"groupId":"1","groupName":"GROUP A","groupRoles":["3"]}]}
foreach ($groupmeta as $value) {
$group_roles = array();
$array = unserialize($value['property_value']);
if ($array[0] == $user_ID) {
//Gets Group ID and Role
$group_id = $value['group_id'];
$group_role = $array[1];
$exists = false;
$group_name_q= json_decode(json_encode($wpdb->get_results($wpdb->prepare('SELECT group_name FROM groups WHERE id=%s', $group_id))), true);
$group_name = $group_name_q[0]['group_name'];
echo $group_role;
echo '<br>';
$group_roles[] = $group_role;
$group_info = array(
'groupId'=>$group_id,
'groupName'=>$group_name,
'groupRoles'=>$group_roles,
);
$groups[] = $group_info;
}
}
$sorted_groups = array();
echo '<br>';
}
$return_arr = array(
"userId"=>$user_ID,
"email"=>$user_email,
"first"=>$user_first,
"last"=>$user_last,
"groups"=>$groups
);
echo json_encode($return_arr);
//var_dump($groupmeta_value);
}

Found an answer, FOREACH runs as a cloned object.
Instead I used the following FOR loop and got the desired results.
$found_group = false;
for ($i = 0; $i < count($groups); $i++) {
if ($groups[$i]['groupId'] == $group_id) {
array_push($groups[$i]['groupRoles'], $group_role);
$found_group = true;
}
}
if (!$found_group) {
//Group Name
$group_name_q= json_decode(json_encode($wpdb->get_results($wpdb->prepare('SELECT group_name FROM groups WHERE id=%s', $group_id))), true);
$group_name = $group_name_q[0]['group_name'];
$group_roles[] = $group_role;
$group_info = array(
'groupId'=>$group_id,
'groupName'=>$group_name,
'groupRoles'=>$group_roles,
);
$groups[] = $group_info;
}

Related

How can I return this array without duplicates in PHP?

I´m trying to get this array
[24]=>
array(2) {
[0]=>
string(1) "21"
[1]=>
string(1) "22"
}
So far I have this:
function Job($conn){
$array = array();
foreach(array_unique($_SESSION['ROLES']) as $value)
{
$sql="SELECT employee,task FROM table WHERE id={$value} AND employee=24";//echo($sql);
$result = $conn->executeSQL($sql);
foreach($result as $value)
{
$array[$value['employee']][] = $value['task'];
}
}
return $array;
}
Which returns the tasks for two values I have store in $_SESSION['ROLES'] but if there are duplicates I need to remove them :
[24]=>
array(4) {
[0]=>
string(1) "21"
[1]=>
string(1) "22"
[2]=>
string(1) "21"
[3]=>
string(1) "22"
}
I can think of two ways to do this.
Use array_unique as indicated by comments.
function Job($conn) {
$array = array();
foreach(array_unique($_SESSION['ROLES']) as $value)
{
$sql="SELECT employee,task FROM table WHERE id={$value} AND employee=24";//echo($sql);
$result = $conn->executeSQL($sql);
$temp = [];
foreach($result as $value)
{
$temp[] = $value['task'];
}
$array[$value['employee']] = array_unique($temp);
}
return $array;
}
Add a conditional to the code to add the element if it does not already exist.
function Job($conn) {
$array = array();
foreach(array_unique($_SESSION['ROLES']) as $value)
{
$sql="SELECT employee,task FROM table WHERE id={$value} AND employee=24";//echo($sql);
$result = $conn->executeSQL($sql);
foreach($result as $value)
{
if ( ! in_array($value['task'], $array[$value['employee']]) )
$array[$value['employee']][] = $value['task'];
}
}
return $array;
}

Adding rows spanning multiple rows in Symfony Console

I am currently developing a CLI using Symfony Console and I have run into a problem regarding adding a row spanning multiple rows.
My code is
$table = new Table($output);
$table->setHeaders(['Elements','Properties']);
foreach($elements as $key => $element) {
if ($key != 'templates') {
//process element
$rowcount = 0;
foreach($element as $name => $component){
if(is_string($component)){
$strings[] = $name.' = '.($component == '' ? 'empty' : $component);
$rowcount++;
}
}
//creating row
$count = 0;
foreach ($strings as $string) {
if ($count == 0) {
$frow[] = new TableCell($key, ['rowspan' => $rowcount]);
$frow[] = $string;
} else {
$row[] = $string;
}
$count++;
}
$rows = [$frow,$row];
var_dump($rows);
$table->addRows($rows);
unset($frow,$row,$strings);
}
}
$table->setStyle('borderless');
$table->render();
The var_dump at this point creates this result
array(2) {
[0]=>
array(2) {
[0]=>
object(Symfony\Component\Console\Helper\TableCell)#63 (2) {
["value":"Symfony\Component\Console\Helper\TableCell":private]=>
string(5) "forms"
["options":"Symfony\Component\Console\Helper\TableCell":private]=>
array(2) {
["rowspan"]=>
int(4)
["colspan"]=>
int(1)
}
}
[1]=>
string(12) "name = forms"
}
[1]=>
array(3) {
[0]=>
string(18) "path = admin/forms"
[1]=>
string(14) "scope = system"
[2]=>
string(16) "attachto = empty"
}
}
The CLI should appear like this
============= ===================
Elements Properties
============= ===================
forms name = forms
path = admin/forms
scope = system
attachto = empty
I don't know if this is too much but the problem is the alignment of the second column is completely disjointed.The scope=system section moves to a 3rd column.

find / select specified ID in array php

i have array with database, and have to select only this items what have "tid" = 1
array(3) {
[1]=>
array(4) {
["tid"]=> "1"
["title"]=> "Google"
["url"]=> "http://google.com/"
["description"]=> "A very efficient search engine."
}
[2]=>
array(4) {
["tid"]=> "2"
["title"]=> "Facebook"
["url"]=> "http://facebook.com/"
["description"]=> "Trade securities, currently supports nearly 1000 stocks and ETFs"
}
[3]=>
array(4) {
["tid"]=> "1"
["title"]=> "Yandex"
["url"]=> "http://yandex.ru/"
["description"]=> "Another efficient search engine popular in Russia"
}
}
how can i select only this items from array what have "tid" = 1?
<?php
$final_arr = array();
foreach($tid_arrs as $tid_arr){
if($tid_arr['tid'] == 1){
$final_arr[] = $tid_arr;
}
}
print_r($final_arr);
?>
$filteredArray = array();
for($i = 0, $end = count($array);$i < $end;i++)
{
if($array[$i]["tid"] === "1")
{
$filderedArray[] = $array[$i];
}
}
That way $filteredArray will contain solely the items with tid 1;
Try array_filter function: http://php.net/manual/en/function.array-filter.php this should help.
print_r(array_filter($array, "filter_function"));
function filter_function($element){
return (int)$element['tid'] === 1;
}
let's say you starting array is $arr.
$result = array();
foreach ($arr as $arrItem) {
if ((array_key_exists('tid', $arrItem)) && ($arrItem['tid'] == "1")){
$result[] = $arrItem;
}
}
$result should be what you are excepted.

PHP: last multidimensional array with end-function

I have a multidimensional array called $response - and the max count is not unqiue. Sometimes it's just 1 up to 4. I want the last array of the second "0":
$last_value = $response['name1'][0]['name2'][0]['name3']['name4'];
...so, if there are
$last_value = $response['name1'][0]['name2'][0]['name3']['name4'];
$last_value = $response['name1'][0]['name2'][1]['name3']['name4'];
$last_value = $response['name1'][0]['name2'][2]['name3']['name4'];
$last_value = $response['name1'][0]['name2'][3]['name3']['name4'];
choose the one with:
$last_value = $response['name1'][0]['name2'][3]['name3']['name4'];
I know, there is the php function end, but I don't get it with the example above.
$last_value = end($response['name1'][0]['name2'])['name3']['name4'];
PHP 5.4+ is required for the Dereferencing of Functions or Methods.
Otherwise it will have to be a two parter for pre PHP 5.4.
$pre = end($response['name1'][0]['name2']);
$last_value = $pre['name3']['name4'];
Testing Environment:
<?php
$response['name1'][0]['name2'][0]['name3']['name4'] = '1';
$response['name1'][0]['name2'][1]['name3']['name4'] = '2';
$response['name1'][0]['name2'][2]['name3']['name4'] = '3';
$response['name1'][0]['name2'][3]['name3']['name4'] = '4';
$myLastElement = end($response['name1'][0]); //Clément Andraud's Answer
$last_value = end($response['name1'][0]['name2'])['name3']['name4'];
var_dump($myLastElement); //Clément Andraud's Output
echo '<br />';
var_dump($last_value);
?>
Testing Results:
array(4) { [0]=> array(1) { ["name3"]=> array(1) { ["name4"]=> string(1) "1" } } [1]=> array(1) { ["name3"]=> array(1) { ["name4"]=> string(1) "2" } } [2]=> array(1) { ["name3"]=> array(1) { ["name4"]=> string(1) "3" } } [3]=> array(1) { ["name3"]=> array(1) { ["name4"]=> string(1) "4" } } }
string(1) "4"
$myLastElement = end($response['name1'][0]);
This doesn't work ?

Illegal Offset Type?

$images = valley_images();
var_dump($images);
$sorted_data = array();
foreach($images as $key => $value) {
if ($key == 'timestamp') {
$sorted_data[$value][] = $images;
}
}
ksort($sorted_data);
The error is appearing on this line:
$sorted_data[$value][] = $images;
When I do the var dump of images I receive this:
array(2) {
[0]=> array(2) {
["id"]=> string(2) "17" ["timestamp"]=> string(10) "1359797773"
}
[1]=> array(2) {
["id"]=> string(2) "20" ["timestamp"]=> string(10) "1359934365"
}
A nice way to do sorting of a key on a multi-dimensional array without having to know what keys you have in the array first:
<?php
$people = array(
array("name"=>"Bob","age"=>8,"colour"=>"red"),
array("name"=>"Greg","age"=>12,"colour"=>"blue"),
array("name"=>"Andy","age"=>5,"colour"=>"purple"));
var_dump($people);
$sortArray = array();
foreach($people as $person){
foreach($person as $key=>$value){
if(!isset($sortArray[$key])){
$sortArray[$key] = array();
}
$sortArray[$key][] = $value;
}
}
$orderby = "name"; //change this to whatever key you want from the array
array_multisort($sortArray[$orderby],SORT_DESC,$people);
var_dump($people);

Categories