Getting largest values from different arrays - php

I want to get the largest values from different arrays. Basically, the arrays are populated from 3 different websites, and I need to know what are the largest tags and photos values of each product.
I have the following array:
$data = array(
'domain1.com' => array(
'id1' => array(
'tags' => '5',
'photos' => '4',
),
'id2' => array(
'tags' => '8',
'photos' => '2',
),
'id3' => array(
'tags' => '6',
'photos' => '1',
),
),
'domain2.com' => array(
'id1' => array(
'tags' => '3',
'photos' => '1',
),
'id2' => array(
'tags' => '4',
'photos' => '9',
),
'id3' => array(
'tags' => '2',
'photos' => '0',
),
),
'domain3.com' => array(
'id1' => array(
'tags' => '7',
'photos' => '3',
),
'id2' => array(
'tags' => '9',
'photos' => '5',
),
'id3' => array(
'tags' => '2',
'photos' => '4',
),
),
);
I need to get the following result:
$data = array(
'id1' => array(
'tags' => '7',
'photos' => '4',
),
'id2' => array(
'tags' => '9',
'photos' => '9',
),
'id3' => array(
'tags' => '6',
'photos' => '4',
),
);

This is solveable with a simple loop:
$new = array();
foreach($data as $domain){
foreach($domain as $id => $_data){
foreach($_data as $elem => $value) {
if(!isset($new[$id][$elem]) || $value > $new[$id][$elem]){
$new[$id][$elem] = $value;
}
}
}
}
Which returns:
Array
(
[id1] => Array
(
[tags] => 7
[photos] => 4
)
[id2] => Array
(
[tags] => 9
[photos] => 9
)
[id3] => Array
(
[tags] => 6
[photos] => 4
)
)
Example

The easiest way is to use nested foreach loops to iterate and capture the data. The results are updated if there is a higher value found in the results array.
$results = [];
foreach ($data as $domain => $items) {
foreach ($items as $id => $elements) {
if (!isset($results[ $id ])) {
$results[ $id ] = [];
}
foreach ($elements as $tag => $value) {
if (!isset($results[ $id ][ $tag ]) || $value>$results[ $id ][ $tag ]) {
$results[ $id ][ $tag ] = $value;
}
}
}
}
print_r($results);

Related

Create Array From Key

Thank you in advance. Is there any way to create a multidimensional array from key names.
$array = array(
'brand/name' => 'BRAND_NAME',
'brand/model' => 'MODEL_NO',
'brand/inv/qty' => '20',
'brand/inv/cost' => '30',
'wh' => 'NY',
'brand/inv/sales' => '40'
);
Transform to this array.
$array = array(
'brand' => array(
'name' => 'BRAND_NAME',
'model' => 'MODEL_NO',
'inv' => array(
'qty' => 20,
'cost' => 30,
'sales' => 40,
)
),
'wh' => 'NY'
);
Thank you !
Try my code (I used the reference operator "&" to get the successive inner arrays):
Input array:
$array = array(
'brand/name' => 'BRAND_NAME',
'brand/model' => 'MODEL_NO',
'brand/inv/qty' => '20',
'brand/inv/cost' => '30',
'wh' => 'NY',
'brand/inv/sales' => '40'
);
php code:
<?php
$resultArray = array();
foreach($array as $path => $element) {
$pathArray = explode("/", $path);
$auxRef = &$resultArray;
foreach($pathArray as $pathPart) {
if(! array_key_exists($pathPart, $auxRef)) {
$auxRef[$pathPart] = array();
}
$auxRef = &$auxRef[$pathPart];
}
$auxRef = $element;
unset($auxRef);
}
?>
Result array:
array ( 'brand' => array ( 'name' => 'BRAND_NAME', 'model' => 'MODEL_NO', 'inv' => array ( 'qty' => '20', 'cost' => '30', 'sales' => '40', ), ), 'wh' => 'NY', )

How can I create an array without duplicates with this structure

I have this array structure:
array (
0 =>
array (
'id' => '17',
'name' => 'aba aba',
'english_name' => 'ABA ABA',
'group_id' => '1',
),
1 =>
array (
'id' => '23',
'name' => 'bcb bcb',
'english_name' => 'BCB BCB',
'group_id' => '2',
),
2 =>
array (
'id' => '17',
'name' => 'aba aba',
'english_name' => 'ABA ABA',
'group_id' => '4',
),
);
I want to create another array with no duplicates but having in mind in which group_id are the duplicate ones. I'm looking for this structure:
array (
17 =>
array (
'name' => 'ABA ABA',
'groups' =>
array (
0 => '1',
1 => '4',
),
),
23 =>
array (
'name' => 'BCB BCB',
'groups' =>
array (
0 => '2',
),
),
);
I tried with this code but it doesn't give me what I'm looking for, I don't know what I'm doing wrong.
Code:
foreach ($array as $value) {
if (!in_array($value['id'], $array[$value['id']] )) {
$interested [$value['id']]['name'] = $value['english_name'];
$interested [$value['id']]['groups'][]= $value['group_id'];
} else if (in_array($value['id'], $array[$value['id']] )){
$interested [$value['id']]['groups'][] = $value['group_id'];
}
}
Simple loop and assign using the id as your pivot:
<?php
$data =
array (
0 =>
array (
'id' => '17',
'name' => 'aba aba',
'english_name' => 'ABA ABA',
'group_id' => '1',
),
1 =>
array (
'id' => '23',
'name' => 'bcb bcb',
'english_name' => 'BCB BCB',
'group_id' => '2',
),
2 =>
array (
'id' => '17',
'name' => 'aba aba',
'english_name' => 'ABA ABA',
'group_id' => '4',
),
);
foreach($data as $item) {
$result[$item['id']]['name'] = $item['english_name'];
$result[$item['id']]['groups'][] = $item['group_id'];
}
var_export($result);
Output:
array (
17 =>
array (
'name' => 'ABA ABA',
'groups' =>
array (
0 => '1',
1 => '4',
),
),
23 =>
array (
'name' => 'BCB BCB',
'groups' =>
array (
0 => '2',
),
),
)
$data = array (
0 =>
array (
'id' => '17',
'name' => 'aba aba',
'english_name' => 'ABA ABA',
'group_id' => '1',
),
1 =>
array (
'id' => '23',
'name' => 'bcb bcb',
'english_name' => 'BCB BCB',
'group_id' => '2',
),
2 =>
array (
'id' => '17',
'name' => 'aba aba',
'english_name' => 'ABA ABA',
'group_id' => '4',
),
);
function unique_multidim_array($array, $key) {
$temp_array = array();
$i = 0;
$key_array = array();
foreach($array as $val) {
if (!in_array($val[$key], $key_array)) {
$key_array[$i] = $val[$key];
$temp_array[$i] = $val;
}
$i++;
}
return $temp_array;
}
$newdata = unique_multidim_array($data,'id');
The function taken from here. Details on : https://www.php.net/manual/tr/function.array-unique.php
It isn't very clear from your code what you are trying to do, but below is one way.
Loop over your subarrays one by one.
have a new array, say $set which will be an associative array of keys and values where keys are the IDs and values are the name and groups attributes.
If $set has the ID isset already, add to groups, else, create a new one and then add groups.
Snippet:
<?php
$set = [];
foreach($array as $val){
$group_id = $val['group_id'];
if(!isset($set[$val['id']])){
$set[$val['id']] = [
'name' => $val['english_name'],
'groups' => []
];
}
$set[$val['id']]['groups'][] = $group_id;
}
print_r($set);
Demo: http://sandbox.onlinephpfunctions.com/code/af65effc35a0275bdf6908c77dc0cb701d36010e
Functional way)
function group( $groups, $item ) {
$id = $item['id'];
if ( !isset($groups[$id]) ) {
$groups[$id] = array (
'name' => $item['name'],
'groups' => array(),
);
}
array_push($groups[$id]['groups'], $item['group_id']);
return $groups;
}
array_reduce($data, 'group', array());
Please take a look at playground
Also to make groups array unique PHP Collections could be used. For example, Set data structure.

Check if key exist in array if so, count it and create a new array php

From my SQL query, I will get the following array as a result. This is the last result I can get from SQL.I cant change any SQL because of some constraint.
I need to check if the same id exists or not and if it does need to count them and remove one of the duplicate array having the same id.
Sample array is
$array = array(
0 => array(
'id' => '17',
'status' => 1,
),
1 => array(
'id' => '18',
'status' => 1,
),
2 => array(
'id' => '21',
'status' => 1,
),
3 => array(
'id' => '5',
'status' => 2,
),
4 => array(
'id' => '18',
'status' => 1,
),
5 => array(
'id' => '22',
'status' => 5,
),
6 => array(
'id' => '6',
'status' => 1,
),
);
I need to check if they have a duplicate id or not, if yes need to count them and remove one of the duplicates.We need to preserve the array structure.
End Results should be
array(
0 => array(
'id' => '17',
'status' => 1,
'count'=1,
),
1 => array(
'id' => '18',
'status' => 1,
'count'=2,
),
2 => array(
'id' => '21',
'status' => 1,
'count'=1,
),
3 => array(
'id' => '5',
'status' => 2,
'count'=1,
),
4 => array(
'id' => '22',
'status' => 5,
'count'=1,
),
5 => array(
'id' => '6',
'status' => 1,
'count'==>1,
),
)
You can Check it by this way but duplicate entry still in the array.
$ids = array();
foreach ($array as $key => $value)
{
$ids[] = $value['id'];
$count = array_count_values($ids);
}
for($i = 0; $i < count($array);$i++)
{
$array[$i]['count'] = $count[$array[$i]['id']];
}
You can do this with the array_unique function.
Use it like so:
$a=array("a"=>"red","b"=>"green","c"=>"red");
print_r(array_unique($a));
Which outputs:
Array ( [a] => red [b] => green )

Extracting data from complicated associative array in php and put into new array

I have an complicated array that looks like this:
$input=array(
(int) 0 => array(
'XXX' => array(
'id' => '7',
'p_id' => '1',
'address' => '9463',
'arrival_time' => '2014-05-01 03:30:00'
),
'YYY' => array(
'id' => '1',
'iden' => '1111',
'name' => 'Tom'
)
),
(int) 1 => array(
'XXX' => array(
'id' => '9',
'p_id' => '2',
'address' => '9469',
'arrival_time' => '2014-05-27 16:43:58'
),
'YYY' => array(
'id' => '2',
'iden' => '2222',
'name' => 'Sam'
)
),
(int) 2 => array(
'XXX' => array(
'id' => '3',
'p_id' => '3',
'address' => '9462',
'arrival_time' => '2014-04-21 14:05:00'
),
'YYY' => array(
'id' => '3',
'iden' => '3333',
'name' => 'James'
)
)
)
I would like to convert it such that it looks like this;
$output=array(
(int) 0 => array(
'name' => 'Tom',
'iden' => '1111',
'address' => '9463'
),
(int) 1 => array(
'name' => 'Sam',
'iden' => '2222',
'address' => '9469'
),
(int) 2 => array(
'name' => 'James',
'iden' => '3333',
'address' => '9462'
)
I wrote some code to solve this problem:
foreach ( $input as $key => $value)
{
$output['name']=$input[$key]['YYY']['name'];
$output['iden']=$input[$key]['YYY']['iden'];
$output['address']=$input[$key]['XXX']['address'];
}
Unfortunately, it retrieves only the last element of the input array.
Can someone more experienced help?
Thank you very much.
You are overwriting the values in each iteration, as you always write to $output['name'] etc.
foreach ( $input as $key => $value)
{
$output[$key] = array(
'name' => $value['YYY']['name'],
'iden' => $value['YYY']['iden'],
'address' => $value['XXX']['address']
);
}
The key here is using $output[$key] instead of $output - this way you will add a new element in each iteration.
Also $input[$key] and $value are equivalent, so I used the shorter variant ;)
Try this in your foreach loop :-
foreach ( $input as $key=>$value)
{
$output[$key]['name']=$value['YYY']['name'];
$output[$key]['iden']=$value['YYY']['iden'];
$output[$key]['address']=$value['XXX']['address'];
}
You have to add an index to the array in the foreach: $output[$key]["name"] = ...;

how to build an array in parent and child manner by fetching mysql data using php

this is my code where i am fetching my mysql record.
$parentChildArr=array();
//mysql query for fetching parent and child record
$selectparentMenu=mysql_query("SELECT `id`,`item_name`,`menu_type`,`parent` FROM `epic_master_menu`");
if(mysql_num_rows($selectparentMenu)>1) {
while($fetchparentMenu=mysql_fetch_array($selectparentMenu)) {
$parentChildArr[]=$fetchparentMenu['id'];
$parentChildArr[]=$fetchparentMenu['item_name'];
$parentChildArr[]=$fetchparentMenu['menu_type'];
$parentChildArr[]=$fetchparentMenu['parent'];
}
var_export($parentChildArr); // exporting or printing arrays
// when i export the array i get this output.
array ( 0 => '1', 1 => 'Dashboard', 2 => 'item', 3 => '0',
4 => '2', 5 => 'Admission', 6 => 'item', 7 => '0', 8 => '3',
9 => 'Examination', 10 => 'item', 11 => '0', 12 => '4',
13 => 'CET', 14 => 'item', 15 => '0');
but the problem is that i want to build the array like this.
$newarr=array ( 'dataSource' => array ( 0 => array ( 'id' => '1',
'text' => 'Dashboard', 'expanded' => 'true', 'spriteCssClass' => 'rootfolder',
'items' => array ( 0 => array ( 'id' => '89', 'text' => 'Users',
'expanded' => true, 'spriteCssClass' => 'folder',
'items' => array ( 0 => array ( 'id' => '94', 'text' => 'Users',
'spriteCssClass' => 'html', ), 1 => array ( 'id' => '94',
'text' => 'Users', 'spriteCssClass' => 'html', ), 2 => array (
'id' => '94', 'text' => 'Users', 'spriteCssClass' => 'image' ) ) ) ) ) ));
database table view is...
i am not getting the logic that how to build the array like $newarr. thank you
not tested, but you need to defined a structure and then you need to go recursive... so you can check where is the parent entry to my child ...
function structure($data){
return array(
'id' => $data['id'],
'item_name' => $data['item_name'],
'menu_type' => $data['menu_type'],
'parent' => $data['parent'],
'expanded' => false,
'childs' => array()
);
}
function recursiveImport(&$parent, $data){
foreach($parent AS $key => $value){
if($value['id'] == $data['parent']){
$parent[$key]['childs'][] = structure($data);
$parent[$key]['expanded'] = true;
return true;
}
else{
if(count($value['childs']) > 0){
foreach($value['childs'] AS $key2 => $child){
$result = recursiveImport($parent[$key]['childs'][$key2], $data);
if($result === true) return true;
}
}
}
}
return false;
}
$newarr = array();
while($fetchparentMenu=mysql_fetch_array($selectparentMenu)) {
$result = recursiveImport($newarr , $fetchparentMenu);
if($result === false){
$newarr[] = structure($fetchparentMenu);
}
}
//output array
array ( 0 => array ( 'id' => '1', 'item_name' => 'Dashboard', 'menu_type' => 'item', 'parent' => '0', 'expanded' => false, 'childs' => array ( ), ), 1 => array ( 'id' => '2', 'item_name' => 'Admission', 'menu_type' => 'item', 'parent' => '0', 'expanded' => false, 'childs' => array ( ), ), 2 => array ( 'id' => '3', 'item_name' => 'Examination', 'menu_type' => 'item', 'parent' => '0', 'expanded' => false, 'childs' => array ( ), ), 3 => array ( 'id' => '4', 'item_name' => 'CET', 'menu_type' => 'item', 'parent' => '0', 'expanded' => false, 'childs' => array ( ), )
Use following code
$m=0;
if(mysql_num_rows($selectparentMenu)>1) {
while($fetchparentMenu=mysql_fetch_array($selectparentMenu)) {
$parentChildArr[$m][]=$fetchparentMenu['id'];
$parentChildArr[$m][]=$fetchparentMenu['item_name'];
$parentChildArr[$m][]=$fetchparentMenu['menu_type'];
$parentChildArr[$m][]=$fetchparentMenu['parent'];
$m++;
}

Categories