Grouping arrays in php and count data - php

Recently I am working on a project that categorises 'Superheros' and 'Supervillains' based on their 'Franchaise' and origin of 'Superpower'. I want to fetch data from database as as Array #1 and displays them as Array #2 in php.
Array #1
Array
(
[0] => Array
(
[id] => 101
[Name] => Superman
[Franchise] => DC Comics
[Superpower] => Inherent
)
[1] => Array
(
[id] => 908
[Name] => Batman
[Franchise] => DC Comics
[Superpower] => Acquired
)
[2] => Array
(
[id] => 228
[Name] => Wolverine
[Franchise] => Marvel
[Superpower] => Acquired
)
[3] => Array
(
[id] => 158
[Name] => Iron Man
[Franchise] => Marvel
[Superpower] => Acquired
)
[4] => Array
(
[id] => 978
[Name] => Thor
[Franchise] => Marvel
[Superpower] => Inherent
)
)
Array #1 elements have to be grouped based on their 'Franchise' and count how many of them are 'Inherent' or 'Acquired' in terms of 'Superpower'.
Array #2
Array
(
[DC Comics] => Array
(
[Inherent] => 1
[Acquired] => 1
)
[Marvel] => Array
(
[Inherent] => 1
[Acquired] => 2
)
)

Here is your code without much logic,
foreach ($array1 as $val) {
if(!isset($array2[$val['Franchise']])) {
$array2[$val['Franchise']] = array('Inherent' => 0, 'Acquired' => 0);
}
$array2[$val['Franchise']][$val['Superpower']]++;
}
print_r($array2);

array_column() function to aggregate an inner key from a 2D array.
array_count_values() function counts all the values of an array.
Use this code snippet for count values:
$a = array ( array ("id" => "101", "Name" => "Superman", "Franchise" => "DC Comics", "Superpower" => "Inherent" ),
array ( "id" => "908", "Name" => "Batman", "Franchise" => "DC Comics", "Superpower" => "Acquired" ),
array ( "id" => "228", "Name" => "Wolverine", "Franchise" => "Marvel", "Superpower" => "Acquired" ),
array ( "id" => "158", "Name" => "Iron Man", "Franchise" => "Marvel", "Superpower" => "Acquired" ),
array ( "id" => "978", "Name" => "Thor", "Franchise" => "Marvel", "Superpower" => "Inherent" ));
echo "<pre>";
$return = array();
// first group array values by franchise
foreach($a as $val) {
if (!isset($return[$val['Franchise']])) {
$return[$val['Franchise']] = array();
}
$return[$val['Franchise']][] = $val;
}
$arr = array();
// count elements by key value pair in particular franchise
foreach ($return as $key => $value) {
$tmp = array_count_values(array_column($value, 'Superpower'));
$arr[$key] = $tmp;
}
print_r($arr);
Demo is here

With single and short array_reduce:
// $arr is your initial array
$result = array_reduce($arr, function($r, $v){
if (isset($r[$v["Franchise"]][$v["Superpower"]])) {
$r[$v["Franchise"]][$v["Superpower"]] += $r[$v["Franchise"]][$v["Superpower"]];
} else {
$r[$v["Franchise"]][$v["Superpower"]] = 1;
}
return $r;
}, []);
print_r($result);
The output:
Array
(
[DC Comics] => Array
(
[Inherent] => 1
[Acquired] => 1
)
[Marvel] => Array
(
[Acquired] => 2
[Inherent] => 1
)
)

Related

Fetch data from 2nd array and put values in the array 1

I have the following situation and cannot find an easy way to do it.
I have 2 arrays:
1)
Array (
[0] => Array
(
[FirstName] => Tom
[LastName] => Siemens
[Id] => 10300
)
[1] => Array
(
[FirstName] => Sam
[LastName] => Tailor
[Id] => 10301
)
2)
Array
(
[0] => Array
(
[Type] => Invoice
[Number] => 6344394
[Project] => Array
(
[Name] => Test Project 1
[ResponsibleUserId] => 10300
[Id] => 498
[ResponsibleUser] =>
)
)
[1] => Array (
[Type] => Invoice
[Number] => 6345555
[Project] => Array
(
[Name] => Test Project 2
[ResponsibleUserId] => 10301
[Id] => 499
[ResponsibleUser] =>
)
)
What could be the best approach to get the "FirstName LastName" from the first array depends on the ID which must equal the Project Id from the second array and to put these values inside the second array -> Project -> ResponsibleUser?
The result I'm looking for is the following:
Final Array)
Array (
[0] => Array
(
[Type] => Invoice
[Number] => 6344394
[Project] => Array
(
[Name] => Test Project 1
[ResponsibleUserId] => 10300
[Id] => 498
[ResponsibleUser] => Tom Siemens
)
)
[1] => Array (
[Type] => Invoice
[Number] => 6345555
[Project] => Array
(
[Name] => Test Project 2
[ResponsibleUserId] => 10301
[Id] => 499
[ResponsibleUser] => Sam Tailor
)
)
If you start by indexing the first array by the id using array_column() ...
$idList = array_column($array1, null, "Id");
You can then just loop over the second array and pick out the name each time and update it...
foreach (array2 as &$project ) {
$id = $project["Project"]["ResponsibleUserId"];
$project["Project"]["ResponsibleUser"] = $idList[$id]["FirstName"]." ".$idList[$id]["LastName"];
}
Use &$project as this allow you to update the original value which is what your after.
Create a new array from array1 with the user id as the keys:
$newArray1 = array();
foreach($array1 as $values)
{
$newArray1[$values['Id']] = $values['FirstName']." ".$values['LastName'];
}
Then
foreach($array2 as $index => $val)
{
$array2[$index]['Project']['ResponsibleUser'] = $newArray1[$val['Project']['ResponsibleUserId'];
}
<?php
$names[0] = array("FirstName" => "Tom", "LastName" => "Siemens", "Id" => 10300);
$names[1] = array("FirstName" => "Sam", "LastName" => "Tailor", "Id" => 10301);
$projects[0] = array("Type" => "Invoice", "Number" => "6344394", "Project" => Array("Name" => "Test Project 1", "ResponsibleUserId" => 10300, "Id" => 498, "ResponsibleUser" => ""));
$projects[1] = array("Type" => "Invoice", "Number" => "6345555", "Project" => Array("Name" => "Test Project 2", "ResponsibleUserId" => 10301, "Id" => 499, "ResponsibleUser" => ""));
foreach ($projects as $pid => $project) {
foreach ($names as $nid => $name) {
if ($project["Project"]["ResponsibleUserId"] == $name["Id"]) {
$projects[$pid]["Project"]["ResponsibleUser"] = $name["FirstName"].' '.$name["LastName"];
};
};
};
print_r($projects);
?>

How do I remove one array from another in php?

I have the following arrays in PHP:
print_r($employees) =
Array
(
[0] => Array
(
[p_id] => T29083999
[name] => Robert Plaxo
)
[1] => Array
(
[p_id] => T29083388
[name] => Yvan Sergei
)
[2] => Array
(
[p_id] => T21083911
[name] => Rhonda Saunders
)
[3] => Array
(
[p_id] => H02910382
[name] => Miguel Mercado
)
)
then this array:
print_r($record) =
Array
(
[0] => Array
(
[c_id] => 1
[section] => 1061
[term] => 201631
[p_id] => T29083388
[c_date] => 2016-04-01 09:14:00
)
)
I want to remove the array element from $employees that matches the p_id of $record. Array $record may have multiple entries like the one shown. If so, any p_id in $record must be removed from $employees.
I tried:
foreach ($employees as $k => $e) {
foreach ($record as $r) {
if ($e['p_id']==$r['p_id']) {
echo "found it!";
// if I uncomment the next line, it crashes! (500 server error)
// unset $employees[$k];
}
}
}
I just want to remove any element from $employees that has any employee that matches any record in $record with that employee id.
You were almost there; just needed parens around your unset()
I also took the liberty to change some of your variable names as single character variable names bother me.
$employees[] = [
'p_id' => 'T29083999',
'name' => 'Robert Plaxo',
];
$employees[] = [
'p_id' => 'T29083388',
'name' => 'Yvan Sergei',
];
$employees[] = [
'p_id' => 'T21083911',
'name' => 'Rhonda Saunders',
];
$employees[] = [
'p_id' => 'H02910382',
'name' => 'Miguel Mercado',
];
$records[] = [
'c_id' => '1',
'section' => '1061',
'term' => '201631',
'p_id' => 'T29083388',
'c_date' => '2016-04-01 09:14:00',
];
foreach ($employees as $key => $employee) {
foreach ($records as $record) {
if ($employee['p_id'] == $record['p_id']) {
echo "found it!";
unset($employees[$key]);
}
}
}
echo "<pre>";
print_r($employees);
Outputs
found it!
Array
(
[0] => Array
(
[p_id] => T29083999
[name] => Robert Plaxo
)
[2] => Array
(
[p_id] => T21083911
[name] => Rhonda Saunders
)
[3] => Array
(
[p_id] => H02910382
[name] => Miguel Mercado
)
)
The short solution using array_column and array_filter functions. It will also fit your requirement "Array $record may have multiple entries":
$p_ids = array_column($record, "p_id");
$employees = array_filter($employees, function($v) use($p_ids){
return !in_array($v["p_id"], $p_ids);
});
print_r($employees);
The output:
Array
(
[0] => Array
(
[p_id] => T29083999
[name] => Robert Plaxo
)
[2] => Array
(
[p_id] => T21083911
[name] => Rhonda Saunders
)
[3] => Array
(
[p_id] => H02910382
[name] => Miguel Mercado
)
)

merging mutidimensional arrays

I have an array that looks like this:
getting array need to convert array as same key value as 0
foreach($array as $key=>$id){
$consumer_data[]=$this->App_model->get_session($id);
}
print_r($consumer_data);
Array
(
[0] => Array
(
[0] => Array
(
[ConsumerID] => 1
[name] => asdfd
)
[1] => Array
(
[ConsumerID] => 5
[name] => test
)
[2] => Array
(
[ConsumerID] => 3
[name] => test1
)
)
[1] => Array
(
[0] => Array
(
[ConsumerID] => 4
[name] => test4
)
)
i want to implement array like this in same key value as 0
Array
(
[0] => Array
(
[0] => Array
(
[ConsumerID] => 1
[name] => asdfd
)
[1] => Array
(
[ConsumerID] => 5
[name] => test
)
[2] => Array
(
[ConsumerID] => 3
[name] => test1
)
[3] => Array
(
[ConsumerID] => 4
[name] => test4
)
)
I am using PHP. Can anyone point me to a good starting point as to how I should go about doing this?
You can use array_merge():
$new_array[0] = array_merge($array[0], $array[1]);
Where $array is the first array.
SEE DEMO
OR for a more dynamic approach:
$new_array = array(0 => array());
foreach($array as $a) {
$new_array[0] = array_merge($new_array[0], $a);
}
SEE DEMO 2
The simpliest solution is to do it with:
$input = array(
array(
array('ConsumerID' => 1, 'name' => 'asdfd'),
array('ConsumerID' => 5, 'name' => 'test'),
array('ConsumerID' => 4, 'name' => 'test1'),
),
array(
array('ConsumerID' => 4, 'name' => 'test4'),
),
);
$output = array(
array()
);
foreach ($input as $data) {
$output[0] = array_merge($output[0], $data);
}
Try this->
$newArray = array();
foreach($values as $key=>$val){
$newArray [0][$key]=$val;
}
print_r($newArray);
Check this:
<?php
$arr[0] = array(0 => array("ConsumerID" => 1, "name" => "Ni"), 1 => array("ConsumerID" => 2, "name" => "Ab"));
$arr[1] = array(1 => array("ConsumerID" =>5, "name" => "GE"), 1 => array("ConsumerID" => 6, "name" => "DB"));
$new = array();
foreach($arr as $key => $value) {
foreach($value as $innerkey => $innervalue) {
$new[0][] = $innervalue;
}
}
print_r($new);
?>

Count occurrences of a value inside a multidimensional array

so i retrieve a json, convert it into an array and i got this output:
Array
(
[Sid] => 23888555
[pages] => Array
(
[0] => Array
(
[id] => 13111071
[name] => Page 1
[slots] => Array
(
[0] => Array
(
[SlotId] => 6
[info] => Array
(
[id] => 5247
[color] => red
)
)
[1] => Array
(
[SlotId] => 4
[info] => Array
(
[id] => 5267
[color] => blue
)
)
[2] => Array
(
[SlotId] => 7
[info] => Array
(
[id] => 5267
[color] => green
)
)
)
)
[1] => Array
(
[id] => 13111072
[name] => Page 2
[slots] => Array
(
[0] => Array
(
[SlotId] => 6
[info] => Array
(
[id] => 5247
[color] => red
)
)
[1] => Array
(
[SlotId] => 4
[info] => Array
(
[id] => 5267
[color] => blue
)
)
)
)
)
)
I have no problem reading it whatsoever, what i wanna do is count for every page how many similar "last" id i got.
Exemple :
[pages][0][slots][0][info][id]
[pages][0][slots][1][info][id]
[pages][0][slots][3][info][id]
For the page 1, I wanna compare these 3 ids between them and count the occurrences.
[pages][1][slots][0][info][id]
[pages][1][slots][1][info][id]
For the page 2, I wanna compare these 2 ids between them and count the occurrences.
The output i want looks like this :
page 1 -> 1x5247
-> 2x5267
page 2 -> 1x5247
-> 1x5267
EDIT :
I tried using
foreach ($data['pages'] as $item) {
foreach ($item['slots'] as $slotnumber => $value) {
print_r(array_count_values($item['slots'][$slotnumber]['info']));
}
}
which returns me this :
Array ( [5247] => 1 [red] => 1 )
Array ( [5267] => 1 [blue] => 1 )
Array ( [5267] => 1 [green] => 1 )
So i think i might be able to use this but i don't know how.
I manually declared the array and then created the countstuff() function. This should work for you. I tested it and it work on my end. After going through all this trouble, I really do appreciated it if you choose my answer and up vote it.
<?php
$data = Array("Sid" => "23888555", "pages" => Array("0" => Array("id" => "13111071", "name" => "Page 1", "slots" => Array("0" => Array("SlotId" => "6", "info" => Array("id" => "5247", "color" => "red")), "1" => Array("SlotId" => "4", "info" => Array("id" => "5267", "color" => "blue")), "2" => Array("SlotId" => "7","info" => Array("id" => "5267", "color" => "green")))),
"1" => Array
(
"id" => "13111072",
"name" => "Page 2",
"slots" => Array
(
"0" => Array
(
"SlotId" => "6",
"info" => Array
(
"id" => "5247",
"color" => "red"
)
),
"1" => Array
(
"SlotId" => "4",
"info" => Array
(
"id" => "5267",
"color" => "blue"
)
)
)
)
)
);
//End of array declaration
//Now the really convoluted coding starts
//Create a function
function countstuff($yourarray){
foreach($yourarray as $mainarraykey => $mainarray){
if($mainarraykey == "pages"){
foreach($mainarray as $pageskey => $pagesarray){
//echo "Page \"$pageskey\"<br/>";
foreach($pagesarray as $pagessubarraykey => $pagessubarray_array){
if($pagessubarraykey == "slots"){
foreach($pagessubarray_array as $slotskey => $slots){
foreach($slots as $slotssubkey => $slotssub){
if($slotssubkey == "info"){
foreach($slotssub as $key => $value){
if($key == "id"){
//echo $value."<br/>";
$pages[$pageskey][] = $value;
}
}
}
}
}
}
}
}
}
}
return $pages;
}
//Execute the countstuff() function
$output = countstuff($data);
function showresults($input){
foreach($input as $pagekey => $page){
echo "Page $pagekey:<br/>";
$results = array_count_values($page);
foreach($results as $resultkey => $result){
echo $result."x".$resultkey."<br/>";
}
echo "<br/>";
}
}
showresults($output);
?>
I tried some things let me know what you guys think of this.
I get every id then enter them into an array then use array_count_values
$array_ids = array();
foreach ($data['pages'] as $item) {
$numberOfElements = count($item['slots']);
$z= 0;
foreach ($item['slots'] as $slotnumber => $value) {
$array_ids[$z] = $item['slots'][$slotnumber]['info']['id'];
// search for occurrences when the array is full
if (count($array_ids) == $numberOfElements) {
var_dump(array_count_values($array_ids));
// reset the array to 0 every time we loop through the whole infos
$array_ids = array();
}
$z++;
}
}
This seems to work for every page.
array (size=2)
5267 => int 2
5247 => int 1
array (size=2)
5267 => int 1
5247 => int 1

Removing duplicates from multidimensional array based on the first elements only PHP

This is the array
Array
(
[0] => Array
(
[artist] => John Keys
[postID] => 254
)
[1] => Array
(
[artist] => Jay Bloom
[postID] => 249
)
[2] => Array
(
[artist] => John Keys
[postID] => 216
)
[3] => Array
(
[artist] => Angie Belle
[postID] => 225
)
)
and I want to remove all duplicates from the artist elements only. Notice that 0 and 2 have the same artist but a different postID. I just want to keep the first occurence of the artist and remove all others. So the result I want to have is
Array
(
[0] => Array
(
[artist] => John Keys
[postID] => 254
)
[1] => Array
(
[artist] => Jay Bloom
[postID] => 249
)
[2] => Array
(
[artist] => Angie Belle
[postID] => 225
)
)
I've tried array_unique and also serializing and doing an array_map, nothing seems to work right.
<?php
$array = Array
(
'0' => Array
(
'artist' => 'John Keys',
'postID' => 254
),
'1' => Array
(
'artist' => 'Jay Bloom',
'postID' => 249
),
'2' => Array
(
'artist' => 'John Keys',
'postID' => 216
),
'3' => Array
(
'artist' => 'Angie Belle',
'postID' => 225
)
);
$newarray = array();
foreach($array as $key => $val){
if(!array_key_exists('artist', $newarray)){
$newarray[$val['artist']] = $val;
}
}
echo '<pre>';
print_r($newarray);
Edit: using numeric keys:
$newarray = array();
$temp = array();
foreach($array as $key => $val){
if(!in_array($val['artist'], $temp)){
$temp[] = $val['artist'];
}
if( !array_key_exists(array_search($val['artist'], $temp), $newarray) ){
$newarray[array_search($val['artist'], $temp)] = $val;
}
}
Simple approach:
$result = array();
foreach ($input as $item) {
if (!array_key_exists($item['artist'], $result)) {
$result[$item['artist']] = $item;
}
}
<?php
$a=array(
"0" => array
(
"artist" => "John Keys",
"postID" => "254"
),
"1" => array
(
"artist" => "Jay Bloom",
"postID" => "249"
),
"2" => array
(
"artist" => "John Keys",
"postID" => "216"
),
"3" => array
(
"artist" => "Angie Belle",
"postID" => "225"
)
);
var_dump($a);
for($i=0;$i<count($a);$i++)
{
for($j=$i+1;$j<count($a); $j++)
{
$tmp1=$a[$i]["artist"];
$tmp2=$a[$j]["artist"];
if($tmp1==$tmp2)
{
unset($a[$j]);
}
$tmp3=array_values($a);
$a=$tmp3;
}
}
var_dump($a);
?>

Categories