Group and merge array row data based on one column - php

I have an array a bit like:
Array (
[1] => Array
(
[1] => 21
[2] => 3
[0] => Analyst
)
[2] => Array
(
[1] => 47
[2] => 8
[0] => Catalysis
)
[3] => Array
(
[1] => 1
[2] => 0
[0] => Biomaterials
)
[4] => Array
(
[3] => 12
[4] => 2
[0] => Analyst
)
[5] => Array
(
[5] => 12
[6] => 2
[0] => Analyst
)
...
However I would like to renumber those entries with the same [0] value so that I end up with
[1] => Array
(
[1] => 21
[2] => 3
[3] => 12
[4] => 2
[5] => 12
[6] => 2
[0] => Analyst
)
So far I've tried getting the [0] values out of the $results array by putting them in their own array and saying if you're already there then add [3] and [4] to where [1] and [2] are in a new array but it's not working.
$final = array();
$jArray = array();
foreach($results as $key => $result) {
if(!in_array($result[0],$jArray) && !empty($result[0])) {
$jArray[$i] = $result[0];
$i++;
}
}
for($x = 0; $x < count($results); $x++) {
$k = array_search($results[$x][0],$jArray);
if(!isset($results[$x][1]))
$final[$k][1] = $results[$x][1];
if(!isset($results[$x][2]))
$final[$k][2] = $results[$x][2];
if(!isset($results[$x][3]))
$final[$k][3] = $results[$x][3];
if(!isset($results[$x][4]))
$final[$k][4] = $results[$x][4];
if(!isset($results[$x][5]))
$final[$k][5] = $results[$x][5];
if(!isset($results[$x][6]))
$final[$k][6] = $results[$x][6];
}
Any simpler ways of doing this?

You can do this way...
$new_arr=array();
$arkeys = array_unique(array_map(function ($v){ return $v[0];},$arr));
foreach($arr as $k=>$arr1)
{
$new_arr[$arr1[0]][]=array_slice($arr1,0,count($arr1)-1);
}
foreach($arkeys as $v)
{
$new_arr[$v] = call_user_func_array('array_merge', $new_arr[$v]);
}
print_r($new_arr);
OUTPUT :
Array
(
[Analyst] => Array
(
[0] => 21
[1] => 3
[2] => 12
[3] => 2
[4] => 12
[5] => 2
)
[Catalysis] => Array
(
[0] => 47
[1] => 8
)
[Biomaterials] => Array
(
[0] => 1
[1] => 0
)
)
Working Demo

If you just want to group by the first element of the sub array, a single loop is enough:
$result = array();
foreach ($array as $sub_arr) {
$key = $sub_arr[0];
unset($sub_arr[0]);
if (!isset($result[$key])) {
$result[$key] = array();
}
$result[$key] += $sub_arr;
}

Here
$final = array();
foreach($results as $key => $result) {
if (!in_array($result[0], array_keys( $final ) ) && !empty($result[0])) {
$final[$result[0]] = array( $result[0] );
}
foreach($result as $k => $v) {
if ($k != 0 && isset($v)) {
$final[$result[0]][$k] = $v;
}
}
}

Related

Find Unique Value from a array

I have a Multidimensional array, I need to find if array have same value of 'brand' attribute then return its id.
I tried via some array functions but it didn't work.
What I Tried:
1)
$backwards = array_reverse($attribute);
echo '<pre>';
$last_item = NULL;
$i = 0;
foreach ($backwards as $current_item) {
if ($last_item === $current_item[$i]['value']) {
echo '<pre>'; print_r($current_item[$i]['value']);
}
$last_item = $current_item[$i]['value'];
echo '<pre>'; print_r($last_item);
$i++;
}
2)
$j = 1;
$i = 0;
foreach ($attributeValues as $attributeData) {
foreach ($attribute as $value) {
if($value[$i]['value'] == $value[$j]['value']) {
echo '<pre>'; print_r($value); die();
}
$j++;
}
}
All my solution's not worked, please help.
[0] => Array
(
[0] => Array
(
[name] => brand
[value] => 54
[id] => 5251
[price] => 15000.0000
)
[1] => Array
(
[name] => model
[value] => 1200
[id] => 5251
[price] => 15000.0000
)
)
[1] => Array
(
[0] => Array
(
[name] => brand
[value] => 54
[id] => 5250
[price] => 15000.0000
)
[1] => Array
(
[name] => model
[value] => 1200
[id] => 5250
[price] => 12000.0000
)
)
[2] => Array
(
[0] => Array
(
[name] => brand
[value] => 89
[id] => 518
[price] => 100.0000
)
[1] => Array
(
[name] => model
[value] => 12
[id] => 518
[price] => 100
)
)
If [name]=>brand and [name]=>model value's of first array is same as second array's value then return [id].
You need two for loop.
$result =[];
foreach ($arr as $key => $value) {
foreach($value as $v){
$result[$v['name']][] = $v['id'];
}
}
$result = array_map("array_unique", $result); // to make it unique
print_r($result);
// if you want to check ids for brand
//print_r($result['brand']);
Output:
Array
(
[brand] => Array
(
[0] => 5251
[1] => 5250
[3] => 518
)
[model] => Array
(
[0] => 5251
[1] => 518
)
)
Demo.
EDIT
Then you can group it by name and value of it
$result =[];
foreach ($arr as $key => $value) {
foreach($value as $v){
$result[$v['name']."|".$v['value']][] = $v['id'];
}
}
$result = array_map("array_unique", $result);
print_r($result);die;
Demo.
you can use foreach and iterate through the array
$res = [];
foreach($arr as $k => $v){
if($v[0]['name'] == $v[1]['name'])
$res[$v[0]['name']] = $v[0]['id'];
}
If you want to match the index value try this
foreach($arr as $k => $v){
if($v[0]['value'] == $v[1]['value'])
$res[] = $v[0]['id'];
}
Working example

rearrange an mutidimention array PHP

I have an array $session that I extract from an awstats file:
# Session range - Number of visits
BEGIN_SESSION 7
1h+ 10
5mn-15mn 9
0s-30s 107
2mn-5mn 7
30s-2mn 21
15mn-30mn 4
30mn-1h 11
END_SESSION
First I wanted to rearrange this by adding the two values of 0s-30s & 30s-2mn and creating another one, here's how I tried it:
$newline="\n";
$lines = explode($newline,$session);
$results = array();
foreach($lines as $line) {
$parts = explode(" ",trim($line),2);
if( count($parts) < 2) continue;
else {
$results[$parts[0]] = intval($parts[1]);
}
}
$temp['0s-30s'] = (isset($results['0s-30s'])?$results['0s-30s']:NULL);
$temp['30s-2mn'] = (isset($results['30s-2mn'])?$results['30s-2mn']:NULL);
$results['0s-2mn'] = $temp['0s-30s'] + $temp['30s-2mn'];
unset($results['0s-30s'],$results['30s-2mn']);
$session = $results['BEGIN_SESSION'].$newline;
foreach($results as $k=>$v) $session .= $k." ".$v.$newline;
$session .= "END_SESSION";
$session = explode("\n", $session) ;
unset($session[(count($session)-1)]) ;
unset($session[0]) ;
unset($session[1]) ;
$sessions = array();
foreach ($session as $key => $value) {
$session[$key] = explode(" ", $value) ;
$sessions[] = array($session[$key][0],trim($session[$key][1])) ;
}
and it displays me this array :
Array
(
[0] => Array
(
[0] => 1h+
[1] => 10
)
[1] => Array
(
[0] => 5mn-15mn
[1] => 9
)
[2] => Array
(
[0] => 2mn-5mn
[1] => 7
)
[3] => Array
(
[0] => 15mn-30mn
[1] => 4
)
[4] => Array
(
[0] => 30mn-1h
[1] => 11
)
[5] => Array
(
[0] => 0s-2mn
[1] => 128
)
)
Is there a way to rearrange my array like this:
Array
(
[0] => Array
(
[0] => 1h+
[1] => 10
)
[1] => Array
(
[0] => 30mn-1h
[1] => 11
)
[2] => Array
(
[0] => 15mn-30mn
[1] => 4
)
[3] => Array
(
[0] => 5mn-15mn
[1] => 9
)
[4] => Array
(
[0] => 2mn-5mn
[1] => 7
)
[5] => Array
(
[0] => 0s-2mn
[1] => 128
)
)
Knowing that $session sometimes come with missing sessions. Any help with this? Thanks.
<?php
$session = 'BEGIN_SESSION 7
1h+ 10
5mn-15mn 9
0s-30s 107
2mn-5mn 7
30s-2mn 21
15mn-30mn 4
30mn-1h 11
END_SESSION';
$newline="\n";
$lines = explode($newline,$session);
$results = array();
foreach($lines as $line) {
$parts = explode(" ", trim($line), 2);
if (in_array($parts[0], array('BEGIN_SESSION', 'END_SESSION'))) continue;
else $results[$parts[0]] = intval($parts[1]);
}
$temp['0s-30s'] = isset($results['0s-30s']) ? $results['0s-30s'] : 0;
$temp['30s-2mn'] = isset($results['30s-2mn']) ? $results['30s-2mn'] : 0;
$results['0s-2mn'] = $temp['0s-30s'] + $temp['30s-2mn'];
unset($results['0s-30s'], $results['30s-2mn']);
$order = array('0s-2mn', '2mn-5mn', '5mn-15mn', '15mn-30mn', '30mn-1h', '1h+');
uksort($results, function($a, $b) use ($order) {
return array_search($a, $order) < array_search($b, $order);
});
var_dump($results);

PHP highlight duplicate values in array [duplicate]

This question already has answers here:
How to detect duplicate values in PHP array?
(13 answers)
Closed 8 years ago.
Ok I am pretty sure there is a simple solution, and I am missing something on this but
lets say I have this a simple array:
Array
(
[0] => 79990
[1] => 79040
[2] => 79100
[3] => 79990
[4] => 79490
[5] => 79290
[6] => 79990
)
0, 3 and 6 are the same value
how do I mark/highlight these values on a foreach loop? result should be something like:
Array
(
[0] => *79990*
[1] => 79040
[2] => 79100
[3] => *79990*
[4] => 79490
[5] => 79290
[6] => *79990*
)
edit: typos
This should do the trick:
<?php
$array = array( '79900',
'79040',
'79100',
'79990',
'79490',
'79290',
'79990');
$count = array_count_values($array);
echo "<pre>".print_r($array, true)."</pre>";
foreach($array as $val)
{
if($count[$val]>1) {
$output[] = "*".$val."*";
} else {
$output[] = $val;
}
}
echo "<pre>".print_r($output, true)."</pre>";
?>
Outputs:
Array
(
[0] => 79900
[1] => 79040
[2] => 79100
[3] => 79990
[4] => 79490
[5] => 79290
[6] => 79990
)
Array
(
[0] => 79900
[1] => 79040
[2] => 79100
[3] => *79990*
[4] => 79490
[5] => 79290
[6] => *79990*
)
Note: Your [0] isn't actually the same as [3] and [6], but I'm assuming this is just a typo
Let me know how you get on!
$array = array("79900","79040","79100","79990","79490","79290","79990");
$count = array_count_values( $array );
$list = array();
foreach( $count as $index => $value ){
if( $value > 1 ){
$list[] = "*" . $index . "*";
}else{
$list[] = $index;
}
}
Note that the repeated index is removed

Arrange PHP Multidimensional Array By Inner Index

How to arrange this array by last inner index ( 0, 1, 2 ) and get the value of the last inner index as the value of each second index:
Array
(
[text] => Array
(
[grid] => Array
(
[0] => 3
[1] => 4
[2] => 5
)
[image] => Array
(
[0] =>
[1] =>
[2] =>
)
[align] => Array
(
[0] => left
[1] => right
[2] => left
)
[title] => Array
(
[0] =>
[1] =>
[2] =>
)
[content] => Array
(
[0] =>
[1] =>
[2] =>
)
)
)
And have the results as below:
Array
(
[text] => Array
(
[0] => Array
(
[grid] => 3
[image] =>
[align] => left
[title] =>
[content] =>
)
[1] => Array
(
[grid] => 4
[image] =>
[align] => right
[title] =>
[content] =>
)
[2] => Array
(
[grid] => 5
[image] =>
[align] => left
[title] =>
[content] =>
)
)
)
This will do the work
function restructure($arr){
$newArr = array();
foreach($arr as $k => $v){
foreach($v as $k1 => $v1){
foreach($v1 as $k2 => $v2){
$newArr[$k][$k2][$k1] = $v2;
}
}
}
return $newArr;
}
As SiGanteng suggested, i dont see other ways than a for/foreach loop:
function buildArray($source, $key = false)
{
// Build the new array
$new_array = array();
// Define groups
$groups = $key === false ? array_keys($source) : array($key);
foreach($groups AS $group)
{
// Get the keys
$keys = array_keys($array[$group]);
// Count the values
$num_entries = count($array[$group][$keys[0]]);
for($i = 0; $i < $num_entries; $i++)
{
foreach($keys AS $key)
{
$new_array[$group][$i][$key] = $array[$group][$key][$i];
}
}
}
return $new_array;
}
This allow you to define the key you need to build; If not specified, the function build the array for every key.
This should work.
function formatit($arr) {
$new = array();
foreach($arr as $k=>$v) {
foreach($v as $k1=>$v1) {
$new[$k1][$k] = $v1;
}
}
return $new;
}
Tested. Call it as
$arr['text'] = formatit($arr['text']);
http://ideone.com/rPzuR

Pairing elements of an multidimensional array

I'm having two arrays in PHP as follows:
Array1 ( [1] => Array ( [0] => 16 )
[2] => Array ( [0] => 17 [1] => 29 )
[3] => Array ( [0] => 30 [1] => 31 )
) Total Element Count: 5
Array2 ( [1] => Array ( [0] => 21 )
[2] => Array ( [0] => 22 )
[3] => Array ( [0] => 23 )
[4] => Array ( [0] => 24 [1] => 25 )
[5] => Array ( [0] => 43 [1] => 44 )
) Total Element Count: 7
I want to pair above two arrays depending on count of first array, that means, first five elements of Array2 should get mixed with Array1 with outer 1D keys remaining intact.
Output should be as follows:
Output Array( [1] => Array ( [0] => 16 [1] => 21)
[2] => Array ( [0] => 17 [1] => 29 [2] => 22)
[3] => Array ( [0] => 30 [1] => 31 [2] => 23 )
[4] => Array ( [0] => 24 [1] => 25 )
)
If you want to avoid E_STRICT warnings:
function combine(array $arr1, array $arr2) {
$ret = array();
foreach ($arr1 as $k => $v) {
if (!array_key_exists($k, $ret)) {
$ret[$k] = array();
}
$ret[$k][] = $v;
}
foreach ($arr2 as $k => $v) {
if (!array_key_exists($k, $ret)) {
$ret[$k] = array();
}
$ret[$k][] = $v;
}
return $ret;
}
If you prefer a shorter version:
function combine(array $arr1, array $arr2) {
$ret = array();
foreach ($arr1 as $k => $v) {
$ret[$k][] = $v;
}
foreach ($arr2 as $k => $v) {
$ret[$k][] = $v;
}
return $ret;
}
What about http://www.php.net/manual/en/function.array-merge-recursive.php :P

Categories