PHP merge arrays by value and merge it's sub arrays - php

I thought I have some understanding of arrays. But it looks like I have no understanding. Or my head don't want to work. I have arrays:
[0] => Array
(
[key] => Person 1
[values] => Array
(
[0] => Array
(
[0] => 1436821440000,12
)
)
)
[1] => Array
(
[key] => Person 2
[values] => Array
(
[0] => Array
(
[0] => 1437562620000,24
)
)
)
[2] => Array
(
[key] => Person 3
[values] => Array
(
[0] => Array
(
[0] => 1437080040000,10
)
)
)
[3] => Array
(
[key] => Person 1
[values] => Array
(
[0] => Array
(
[0] => 1437082860000,1
)
)
)
[4] => Array
(
[key] => Person 3
[values] => Array
(
[0] => Array
(
[0] => 1437081840000,9
)
)
)
And here is what I want to achieve:
[0] => Array
(
[key] => Person 1
[values] => Array
(
[0] => Array
(
[0] => 1436821440000,12
[1] => 1437082860000,1
)
)
)
[1] => Array
(
[key] => Person 2
[values] => Array
(
[0] => Array
(
[0] => 1437562620000,24
)
)
)
[2] => Array
(
[key] => Person 3
[values] => Array
(
[0] => Array
(
[0] => 1437080040000,10
[1] => 1437081840000,9
)
)
)
How could I remove duplicates and merge data?

The sample input doesn't offer any variation in the data contained in the deept subarrays, so I'll demonstrate the utility of my snippet by adding a little more complexity in the data.
Effectively, each time a new key is encountered, you declare a new row containing the key element and a values element with an empty array. To identify that key as "encountered", the new row is assigned to the result array using the key value as the first level key.
Now that the values subarray is guaranteed to be declared, an inner loop will comb through the deeper arrays and push one or more (all) deep values into the respective values subarray -- in a flat fashion.
Code: (Demo)
$array = [
['key' => 'Person 1', 'values' => [['1436821440000,12']]],
['key' => 'Person 2', 'values' => [['1437562620000,24']]],
['key' => 'Person 3', 'values' => [['1437080040000,10']]],
['key' => 'Person 1', 'values' => [['1437082860000,1'], ['1437082860000,2', '1437082860000,3']]],
['key' => 'Person 3', 'values' => [['1437081840000,9']]],
];
$result = [];
foreach ($array as $row) {
if (!isset($result[$row['key']])) {
$result[$row['key']] = ['key' => $row['key'], 'values' => []];
}
foreach ($row['values'] as $values) {
array_push($result[$row['key']]['values'], ...$values);
}
}
var_export(
array_values($result)
);
Output:
array (
0 =>
array (
'key' => 'Person 1',
'values' =>
array (
0 => '1436821440000,12',
1 => '1437082860000,1',
2 => '1437082860000,2',
3 => '1437082860000,3',
),
),
1 =>
array (
'key' => 'Person 2',
'values' =>
array (
0 => '1437562620000,24',
),
),
2 =>
array (
'key' => 'Person 3',
'values' =>
array (
0 => '1437080040000,10',
1 => '1437081840000,9',
),
),
)

$result_arr = array();
foreach ($arr as $sub_arr)
{
$result_arr = array_merge($result_arr, $sub_arr);
$result_arr = array_unique($result_arr);
}

Related

PHP - How To Grouping if value same in array

This my array example
Array
(
[0] => Array ( [_id] => 5f76b1788ee23077dccd1a2c [product] => Array ( [0] => Array ( [_id] => 5d0391a4a72ffe76b8fcc610 ) ) [count] => 1 )
[1] => Array ( [_id] => 5f76b6288ee2300700cd1a3a [product] => Array ( [0] => Array ( [_id] => 5d0391b6a72ffe76b8fcc611 ) ) [count] => 1 )
[2] => Array ( [_id] => 5f76d2488ee23083d3cd1a4a [product] => Array ( [0] => Array ( [_id] => 5d0391b6a72ffe76b8fcc611 ) ) [count] => 1)
)
And i want to group if product value same, like this,
Array
(
[0] => Array ( [_id] => 5f76b1788ee23077dccd1a2c [product] => Array ( [0] => Array ( [_id] => 5d0391a4a72ffe76b8fcc610 ) ) [count] => 1 )
[1] => Array ( [_id] => 5f76b6288ee2300700cd1a3a [product] => Array ( [0] => Array ( [_id] => 5d0391b6a72ffe76b8fcc611 ) ) [count] => 2 )
)
It makes no sense to retain the first level ids since you are arbitrarily trashing some of the first level ids (damaging the relationships) during the merging process.
Instead I recommend that you only isolate the data that is accurately related.
If this output does not serve your needs, then I'll ask for further question clarification.
By assigning temporary keys to your output array, the output array also acts as a lookup array by which you can swiftly check for uniqueness. The "null coalescing operator" (??) sets a fallback value of 0 when an id is encountered for the first time -- this prevents generating any warnings regarding undeclared keys.
Code: (Demo)
$array = [
['_id' => '5f76b1788ee23077dccd1a2c', 'product' => ['_id'=>'5d0391a4a72ffe76b8fcc610'], 'count'=> 1],
['_id' => '5f76b6288ee2300700cd1a3a', 'product' => ['_id'=>'5d0391b6a72ffe76b8fcc611'], 'count'=> 1],
['_id' => '5f76d2488ee23083d3cd1a4a', 'product' => ['_id'=>'5d0391b6a72ffe76b8fcc611'], 'count'=> 1]
];
$productCounts = [];
foreach ($array as $item) {
$productId = $item['product']['_id'];
$productCounts[$productId] = ($productCounts[$productId] ?? 0) + $item['count'];
}
var_export($productCounts);
Output:
array (
'5d0391a4a72ffe76b8fcc610' => 1,
'5d0391b6a72ffe76b8fcc611' => 2,
)
If you insist of the desired output in your question, then it can be as simple and efficient as this...
Code: (Demo)
$result = [];
foreach ($array as $item) {
$productId = $item['product']['_id'];
if (!isset($result[$productId])) {
$result[$productId] = $item;
} else {
$result[$productId]['count'] += $item['count'];
}
}
var_export(array_values($result));
Output:
array (
0 =>
array (
'_id' => '5f76b1788ee23077dccd1a2c',
'product' =>
array (
'_id' => '5d0391a4a72ffe76b8fcc610',
),
'count' => 1,
),
1 =>
array (
'_id' => '5f76b6288ee2300700cd1a3a',
'product' =>
array (
'_id' => '5d0391b6a72ffe76b8fcc611',
),
'count' => 2,
),
)
You can try the below code it will work for you :-)
<?php
$Myarray = array(['_id'=> '5f76b1788ee23077dccd1a2c', 'product'=> ['_id'=>'5d0391a4a72ffe76b8fcc610'] ,'count'=> 1 ],
['_id'=> '5f76b6288ee2300700cd1a3a', 'product'=> ['_id'=>'5d0391b6a72ffe76b8fcc611'] ,'count'=> 1 ],
['_id'=> '5f76d2488ee23083d3cd1a4a', 'product'=> ['_id'=>'5d0391b6a72ffe76b8fcc611'] ,'count'=> 1 ]
);
$user_array = [];
$temp_array = [];
foreach($Myarray as $temp)
{
$found = array_search($temp['product']['_id'], $temp_array);
if($found !== false)
{
$i = 0;
foreach($user_array as $temp1)
{
if($temp1['product']['_id'] == $temp['product']['_id'])
{
$sum = $temp1['count'] + 1;
$user_array[$i]['count'] = $sum;
}
$i++;
}
}
else
{
array_push($user_array,$temp);
array_push($temp_array,$temp['product']['_id']);
}
}
print_r($user_array);
?>
This will produce below Output
Array ( [0] => Array ( [_id] => 5f76b1788ee23077dccd1a2c [product] => Array ( [_id] => 5d0391a4a72ffe76b8fcc610 ) [count] => 1 ) [1] => Array ( [_id] => 5f76b6288ee2300700cd1a3a [product] => Array ( [_id] => 5d0391b6a72ffe76b8fcc611 ) [count] => 2 ) )

change a key of a single element array

I have an array tree from a database, I want to change the key of a child element in this case the second array 'eric'=>array into integer '0'=>array as follow :
0 => Array
('text' => 'paris',
'nodes' => Array
('eric' => Array
( 'text' => 'eric',
'nodes' => Array
(0 => Array
(
'text' => 'so.png',
),
),
),
),
),
there is my code :
while($d = mysqli_fetch_assoc($result)) {
if(!isset($data[$d['country']])) {
$data[$d['country']] = array(
'text' => $d['country'],
'nodes' => array()
);
}
if(!isset($data[$d['country']]['nodes'][$d['name']])) {
$data[$d['country']]['nodes'][$d['name']] = array(
'text' => $d['name'],
'nodes' => array()
);
}
array_push($data[$d['country']]['nodes'][$d['name']]['nodes'], $d['n_doc']);
}
To change all of the child keys to numeric values, you can simply just use array_values()
Live Demo
for($i = 0; $i <= count($data) -1; $i++) { # This loops through each country
$data[$i]['nodes'] = array_map(function($node) { # This preserves the parent text value
return array_values($node); # [0] => Paris, [1] => array(...)
}, $data[$i]['nodes']);
}
Output
[ ... => [ text => Paris, nodes => [ 0 => Paris, 1 => [ ... ] ] ... ] ... ]
can you change your code for this input:
Array
(
[0] => Array
(
[text] => paris
[nodes] => Array
(
[jacque] => Array
(
[text] => jacque
[nodes] => Array
(
[0] => 32.png
)
)
[anis] => Array
(
[text] => anis
[nodes] => Array
(
[0] => 5384a97ee9d6b (2).pd
)
)
)
)
[1] => Array
(
[text] => london
[nodes] => Array
(
[dodo] => Array
(
[text] => dodo
[nodes] => Array
(
[0] => 148782.svg
[1] => 333.png
)
)
[sd] => Array
(
[text] => sd
[nodes] => Array
(
[0] => 1014-favicon.ico
)
)
)
)
)

PHP multiple array sorting method

If I have this array:
//$myarray
Array (
[0] => Array (
[b163cb25371a1b7c550d8f69fe211cc8] => Array (
[unique_key] => 14f74cf38563b889386beeec511033e2
[thwepof_options] => Array (
[order_date] => Array (
[name] => order_date
[value] => 1
[label] => Szállítási nap
[options] =>
)
)
)
)
)
How can I write a sorting method which sort the values by order_date [value]
I've tried first to get the array column like this but didn't got any return value:
<?php
$days = array_column($myarray[0]['thwepof_options'], 'value', 'order_date');
?>
You are skipping the 2nd level key.
Here's a working version of your code:
<?php
$myarray = Array (
0 => Array (
'b163cb25371a1b7c550d8f69fe211cc8' => Array (
'unique_key' => '14f74cf38563b889386beeec511033e2',
'thwepof_options' => Array (
'order_date' => Array (
'name' => 'order_date',
'value' => 1,
'label' => 'Szállítási nap',
'options' => null
)
)
)
)
);
$days = array_column($myarray[0]['b163cb25371a1b7c550d8f69fe211cc8']['thwepof_options'], 'value', 'order_date');
print_r($days);
Also, this thing looks to me like it would make more sense as an object.

How to combine each subarray of subarrays and store them as comma separated strings?

I need to join all subarray Name values in single subarray.
Given input format:
Array
(
[0] => Array
(
[0] => Array
(
[Name] => kumar
)
[1] => Array
(
[Name] => siva
)
)
[1] => Array
(
[0] => Array
(
[Name] => Arun
)
[1] => Array
(
[Name] => Prem
)
)
)
required output format
Array
(
[0] => Array
(
[0] => Array
(
[Name] => kumar, siva
)
)
[1] => Array
(
[0] => Array
(
[Name] => Arun, Prem
)
)
)
My coding attempt:
$final = array();
foreach ($NameArray as $row) {
foreach ($row as $rows) {
$final[] = $rows['Name'];
}
}
print_r($final);
It shows each separate. I need each subarray to be a single array name with comma format.
You can do something like this:
foreach($a as $k1=>$ar1){
$text = '';
foreach($ar1 as $t){
$text .= "{$t['Name']}, ";
}
unset($a[$k1]);
$a[$k1][0]['Name'] = substr($text,0,-2);
}
var_dump($a);
Output:
array (size=2)
0 =>
array (size=1)
0 =>
array (size=1)
'Name' => string 'kumar, siva' (length=10)
1 =>
array (size=1)
0 =>
array (size=1)
'Name' => string 'Arun, Prem' (length=9)
This can be solved succinctly with one loop and the implosion of the columnar values in each subarray.
Code (Demo)
$a = [
[['Name' => 'kumar'],['Name' => 'siva']],
[['Name' => 'Arun'],['Name' => 'Prem']]
];
foreach ($a as $i => $group) {
$result[$i][] = ['Name' => implode(', ', array_column($group, 'Name'))];
}
var_export($result);
Output:
array (
0 =>
array (
0 =>
array (
'Name' => 'kumar, siva',
),
),
1 =>
array (
0 =>
array (
'Name' => 'Arun, Prem',
),
),
)

Sort a set of arrays based on a single key:value pair in php

Found a question which already explains this - How to sort an array of associative arrays by value of a given key in PHP?
I have an array (A1) of arrays (A2). I would like to sort all A2s inside A1 based on a key:value pair in A2
The structure is like this
A1
->A2-1
->K1:Some Value
->K2:ValB
->A2-2
->K1:Other Value
->K2:ValB1
->A2-3
->K1:Some Value
->K2:ValB2
->A2-4
->K1:Other Value
->K2:ValB3
I would like to sort the arrays in A1 so that all A2s for which K1's value is Other Value are bunched together and all A2s for which K1's value is Some Value are bunched together
So after the sorting, the final order of arrays in A1 should be A2-2, A2-4, A2-1, A2-3. Is there a function in PHP using which I can do this? Or do I have to parse through the entire array and do the sorting?
Thanks.
http://php.net/manual/en/function.array-multisort.php
If that doesn't fit, there's a lot of other array functions http://www.php.net/manual/en/ref.array.php
Have a try with:
$A1 = array(
'A2-1' => array(
'K1' => 'Some Value',
'K2' => 'ValB',
),
'A2-2' => array(
'K1' => 'Other Value',
'K2' => 'ValB1',
),
'A2-3' => array(
'K1' => 'Some Value',
'K2' => 'ValB2',
),
'A2-4' => array(
'K1' => 'Other Value',
'K2' => 'ValB3',
)
);
function mySort($a, $b) {
if ($a['K1'] == $b['K1']) {
return strcmp($a['K2'], $b['K2']);
} else {
return strcmp($a['K1'], $b['K1']);
}
}
uasort($A1, 'mySort');
print_r($A1);
output:
Array
(
[A2-2] => Array
(
[K1] => Other Value
[K2] => ValB1
)
[A2-4] => Array
(
[K1] => Other Value
[K2] => ValB3
)
[A2-1] => Array
(
[K1] => Some Value
[K2] => ValB
)
[A2-3] => Array
(
[K1] => Some Value
[K2] => ValB2
)
)
You need something like:
usort($array, function($a, $b)
{
return strcmp($a['k1'], $b['k1']);
});
You may need to replace strcmp with a different sorting function (or operators) because it's unclear exactly what you are doing.
strategy:
1. find unique values, put them aside.
2. loop through unique values
2.1 loop origial array
2.2 store sub array in $out if unique val = original val
<?php
$i=0;
$a3d = array(
$i++ => array(0=>'Some Value',1=>'ValB'),
$i++ => array(0=>'Other Value',1=>'ValB1'),
$i++ => array(0=>'Some Value',1=>'ValB2'),
$i++ => array(0=>'Zome moar',1=>'ValB4'),
$i++ => array(0=>'Other Value',1=>'ValB3'),
$i++ => array(0=>'Zome Moar',1=>'ValB4'),
);
print_r($a3d);
foreach ($a3d as $a2d){
$uniq[]= $a2d[0];
}
$uniq = array_unique($uniq);
sort($uniq);
print_r($uniq);
foreach ($uniq as $v){
foreach ($a3d as $kk => $a2d){
if ($a2d[0] == $v){
$out[]= $a2d;
unset($a3d[$kk]); // <--avoid rechecking elements
}
}
}
print_r(count($a3d));
print_r($out);
?>
$ php sort_array.php
Array
(
[0] => Array
(
[0] => Some Value
[1] => ValB
)
[1] => Array
(
[0] => Other Value
[1] => ValB1
)
[2] => Array
(
[0] => Some Value
[1] => ValB2
)
[3] => Array
(
[0] => Zome moar
[1] => ValB4
)
[4] => Array
(
[0] => Other Value
[1] => ValB3
)
[5] => Array
(
[0] => Zome Moar
[1] => ValB4
)
)
Array
(
[0] => Other Value
[1] => Some Value
[2] => Zome Moar
[3] => Zome moar
)
0Array
(
[0] => Array
(
[0] => Other Value
[1] => ValB1
)
[1] => Array
(
[0] => Other Value
[1] => ValB3
)
[2] => Array
(
[0] => Some Value
[1] => ValB
)
[3] => Array
(
[0] => Some Value
[1] => ValB2
)
[4] => Array
(
[0] => Zome Moar
[1] => ValB4
)
[5] => Array
(
[0] => Zome moar
[1] => ValB4
)
)

Categories