take indexes between repeated values - php

how can I get everything from a repeated index and the other in an array? see:
$Produtos = Array( 'Guitarra' , // repeats
'Bateria' , // repeats
'Piano' ,
'Baixo' ,
'Guitarra' , // repeats
'Violão' ,
'Caixas de Som' ,
'Bateria' , // repeats
'Sanfona' );
Reviewed are the indices that are repeated, as I do to get what's between them?
I wish to return:`
Array
(
[0] => Array(
[0] => Piano
[1] => Baixo
[1] => Array(
[0] => Violão
[1] => Caixas de Som
[2] => Array(
[0] => Sanfona
) )

It can be solved like this:
<?php
<?php
$Produtos = Array( 'Guitarra' , // repeats
'Bateria' , // repeats
'Piano' ,
'Baixo' ,
'Guitarra' , // repeats
'Violão' ,
'Caixas de Som' ,
'Bateria' , // repeats
'Sanfona' );
$countedProducts = array_count_values($Produtos);
$c = 0;
foreach ($Produtos as $product)
{
if ($countedProducts[$product] > 1)
{
if (count($novosProdutos))
{
$c++;
}
}else{
$novosProdutos[$c][] = $product;
}
}
print '<pre>';
var_dump($novosProdutos);
print '</pre>';
?>
Output:
array(3) {
[0]=>
array(2) {
[0]=>
string(5) "Piano"
[1]=>
string(5) "Baixo"
}
[1]=>
array(2) {
[0]=>
string(7) "Violão"
[1]=>
string(13) "Caixas de Som"
}
[2]=>
array(1) {
[0]=>
string(7) "Sanfona"
}
}
I have understood in the meantime, what you really wanted to have as an result. I changed it now, and it work also with multiple repeations and starts always from zero.

$finalProducts = array();
$currentKey = 0;
$wordCount = array_count_values($Produtos);
foreach($Produtos as $val) {
if($wordCount[$val] > 1) {
$currentKey++;
}
elseif(strlen($currentKey) > 0) {
$finalProducts[$currentKey][] = $val;
}
}
$finalProducts = array_values($finalProducts);

<?php
function array_between_duplicates($ary)
{
// first, tally up all the values
// we need to know how many times each value repeats
$count = array_count_values($ary);
// next, we want only the values that are not repeated.
// This can be done by filtering the array for values
// present 2+ times
$between = array_filter($count, create_function('$a','return $a==1;'));
// now that we have the unique values, swap the keys
// and value locations using array_keys
$swap = array_keys($between);
// and then intersect the new array with the original
// array so we can get back their original key values.
$intersect = array_intersect($ary, $swap);
var_dump($intersect);
// now, in order to get the nested groups we will use
// skipped keys as a sign that the in-between values
// were repeats. So, iterate over the array and break
// out these groups
$result = array(); $group = array();
foreach ($ary as $key => $value)
{
if (!array_key_exists($key, $intersect) && count($group) > 0)
{
$result[] = $group;
$group = array();
}
if (array_search($value,$intersect) !== false)
$group[] = $value;
}
if (count($group) > 0)
$result[] = $group;
// return the result
return $result;
}
var_dump(array_between_duplicates($Produtos));
Results in:
array(3) {
[0]=>
array(2) {
[0]=>
string(5) "Piano"
[1]=>
string(5) "Baixo"
}
[1]=>
array(2) {
[0]=>
string(7) "Violão"
[1]=>
string(13) "Caixas de Som"
}
[2]=>
array(1) {
[0]=>
string(7) "Sanfona"
}
}
DEMO

Related

Remove duplicates from PHP which has multiple arrays [duplicate]

This question already has answers here:
Filter/Remove rows where column value is found more than once in a multidimensional array
(4 answers)
Closed 9 months ago.
This is the current output I have from an array by doing var_dump($getvals):
array(2) {
["value"]=>string(5) "150mm"
["label"]=>string(5) "150mm"
}
array(2) {
["value"]=>string(5) "150mm"
["label"]=>string(5) "150mm"
}
array(2) {
["value"]=>string(5) "150mm"
["label"]=>string(5) "150mm"
}
array(2) {
["value"]=>string(5) "150mm"
["label"]=>string(5) "150mm"
}
array(2) {
["value"]=>string(5) "125mm"
["label"]=>string(5) "125mm"
}
array(2) {
["value"]=>string(5) "125mm"
["label"]=>string(5) "125mm"
}
What I want to achieve is first of all, to ignore the ['label'] tables and then try removing any duplicates (150mm and 125mm). I have tried both array_unique and !inarray() but it won't work. Here is my code:
$getvals = get_sub_field('option_diameter'); // This is my array
$takens = array(); // I create an empty array for later on
foreach ($getvals as $key => $getval){ // Running through the array
if ($key == 'value'){ // Ignoring Label table
if(!in_array($getval, $takens)){ // Check if the current value is already inside $takens array
$takens[] = $getval; // If not, then put it
}
}
}
var_dump($takens); // The output is below
This is what I get from var_dump($takens) :
array(1) {
[0]=>string(5) "150mm"
}
array(1) {
[0]=>string(5) "150mm"
}
array(1) {
[0]=>string(5) "150mm"
}
array(1) {
[0]=>string(5) "150mm"
}
array(1) {
[0]=>string(5) "125mm"
}
array(1) {
[0]=>string(5) "125mm"
}
The duplicate values are not removed. Any ideas?
Use a key to remove the duplicate, Demo
$result = [];
foreach($array as $arr){
$result[$arr['value']] = $arr;
}
print_r(array_values($result));
You need to first fetch value by using array_diff_key. Then you need to use array_column, in which passing null as second parameter and unique by value as key to removing duplicates(as keys can not be duplicated). Then to reset indexes array_values
Here is the script,
$takens = array_values(array_column(array_map(function ($a) {
return array_diff_key($a, ['label' => '']);
}, $getvals), null, 'value'));
Demo
Output:-
array(2) {
[0]=>
array(1) {
["value"]=>
string(5) "150mm"
}
[1]=>
array(1) {
["value"]=>
string(5) "125mm"
}
}
You can use array_column
$r = array_values(array_column($a, null, 'label'));
OR
if you want to keep single column
$r = array_values(array_column($a, 'value', 'label'));
print_r($r);
array_values will reorder the keys of the array
Working example :- https://3v4l.org/n8SA1
It look like you forgot a foreach.
Here a test done a few minutes ago :
$aArrayTest = array (
array(
'value'=>'150mm',
'label'=>'150mm'
),
array(
'value'=>'150mm',
'label'=>'150mm'
),
array(
'value'=>'150mm',
'label'=>'150mm'
),
array(
'value'=>'150mm',
'label'=>'150mm'
),
array(
'value'=>'125mm',
'label'=>'125mm'
),
array(
'value'=>'125mm',
'label'=>'125mm'
)
);
$aArrayResult = array();
foreach ($aArrayTest as $aArray) { // Running through the array of Arrays
foreach ($aArray as $key => $value){ // Running through each array
if ($key == 'value'){ // Ignoring Label table
if(!in_array($value, $aArrayResult)){ // Check if the current value is already inside $takens array
$aArrayResult[] = $value; // If not, then put it
}
}
}
}
var_dump($aArrayResult);</pre>

PHP: How to get unique content from array?

I have a array and I need unique contents. How can I get rid of duplicates in this $tmparray:
array(176) {
[0]=>
array(2) {
[0]=>
string(22) "/ads/67006/didi"
[1]=>
string(73) "/Content/Pictures/Scaled/7b5c69572fdb1569ced695c278072ae0.jpg"
}
[1]=>
array(2) {
[0]=>
string(22) "/ads/67006/didi"
[1]=>
string(73) "/Content/Pictures/Scaled/7b5c69572fdb1569ced695c278072ae0.jpg"
}
[2]=>
array(2) {
[0]=>
string(22) "/ads/67006/didi"
[1]=>
string(73) "/Content/Pictures/Scaled/7b5c69572fdb1569ced695c278072ae0.jpg"
}
[3]=>
array(2) {
[0]=>
string(19) "/ads/67010/sylvesta"
[1]=>
string(73) "/Content/Pictures/Scaled/83ebba04b8eabd0458cc6dbbb85581da.jpg"
}
[4]=>
array(2) {
[0]=>
string(19) "/ads/67010/sylvesta"
[1]=>
string(73) "/Content/Pictures/Scaled/83ebba04b8eabd0458cc6dbbb85581da.jpg"
}
[5]=>
array(2) {
[0]=>
string(19) "/ads/67010/sylvesta"
[1]=>
string(73) "/Content/Pictures/Scaled/83ebba04b8eabd0458cc6dbbb85581da.jpg"
}
But I want it to look like: (Only unique contents.)
array(176) {
[0]=>
array(2) {
[0]=>
string(22) "/ads/67006/didi"
[1]=>
string(73) "/Content/Pictures/Scaled/7b5c69572fdb1569ced695c278072ae0.jpg"
}
[1]=>
array(2) {
[0]=>
string(19) "/ads/67010/sylvesta"
[1]=>
string(73) "/Content/Pictures/Scaled/83ebba04b8eabd0458cc6dbbb85581da.jpg"
}
}
I have tried with:
array_unique($tmparray);
array_unique can't do what I want. Anyone have a idea how to solve this?
your question seems duplicate of this
How to remove duplicate values from a multi-dimensional array in PHP
i guess array_map will solve your problem
$input = array_map("unserialize", array_unique(array_map("serialize", $input)));
You can use this code:
$newarray= array();
foreach ($tmparray as $value) {
if (!in_array($value,$newarray)) {
$newarray[ ] = $value;
}
}
var_dump($newarray);
I assume that by duplicate you mean two items where either elements are matching, since you are mapping ads to their pictures, therefore:
$target = array();
$elementCount = count($tmparray);
$newElementCount = 0;
for ($i = 0; $i < $elementCount; $i++) {
$found = false;
for ($j = 0; (!$found) && (j < $newElementCount); j++) {
$found = $target[$j][0] === $tmparray[$i][0] || $target[$j][1] === $tmparray[$i][1];
}
if (!$found) {
$target[$newElementCount++]=$tmparray[$i];
}
}
PHP array_unique is used only for single dimensional arrays, for multidimensional you can do this by serializing multidimensional array, like below
<?php
$dataArray = [
0=>["/ads/67006/didi","/Content/Pictures/Scaled/7b5c69572fdb1569ced695c278072ae0.jpg"],
1=>["/ads/67010/sylvesta","/Content/Pictures/Scaled/83ebba04b8eabd0458cc6dbbb85581da.jpg"],
2=>["/ads/67006/didi","/Content/Pictures/Scaled/7b5c69572fdb1569ced695c278072ae0.jpg"],
3=>["/ads/67010/sylvesta","/Content/Pictures/Scaled/83ebba04b8eabd0458cc6dbbb85581da.jpg"],
];
$serilaized = [];
$newArr = [];
### serilaize each node of multi array and create a new single dimention array..
foreach($dataArray as $val){
$serilaized[] = serialize($val);
}
### now perform array unique..
$serilaized_unique = array_unique($serilaized);
## unserialize each node of uniqur array..
foreach($serilaized_unique as $val){
$newArr[] = unserialize($val);
}
echo "<pre>";print_r($newArr);
?>
This will give you:
Array
(
[0] => Array
(
[0] => /ads/67006/didi
[1] => /Content/Pictures/Scaled/7b5c69572fdb1569ced695c278072ae0.jpg
)
[1] => Array
(
[0] => /ads/67010/sylvesta
[1] => /Content/Pictures/Scaled/83ebba04b8eabd0458cc6dbbb85581da.jpg
)
)
In short you can perform this in single line code with array_map
$dataArray = array_map('unserialize', array_unique(array_map('serialize', $dataArray)));
I got it working with this line:
$tmparray = array_unique($tmparray, SORT_REGULAR);

PHP Arrays - Merge two arrays where a value is added together

I need some more help regarding PHP Arrays and the issue I am having. I have an array like this: -
array(2) {
[0]=>
array(2) {
[0]=>
array(2) {
["count"]=>
string(3) "100"
["id"]=>
int(46)
}
[1]=>
array(2) {
["count"]=>
string(3) "300"
["id"]=>
int(53)
}
}
[1]=>
array(1) {
[0]=>
array(2) {
["count"]=>
string(3) "200"
["id"]=>
int(46)
}
}
}
However, I would like it to look more like this as array: -
array(2) {
[0]=>
array(2) {
["count"]=>
string(3) "300" <--- This has been added from Array 1 and 2
["id"]=>
int(46)
}
[1]=>
array(2) {
["count"]=>
string(3) "300"
["id"]=>
int(53)
}
}
Basically if the same id is in both areas I want the count number to be added to each other but if it's not then it needs to just be left alone and included in the array.
I have used a number of array functions such as array_merge and array_push but I am running out of ideas of how this could work. I have also started working on a foreach with if statements but I just got myself completely confused. I just need a second pair of eyes to look at the issue and see howe it can be done.
Thanks again everyone.
Should work with something like this:
$idToCountArray = array(); //temporary array to store id => countSum
array_walk_recursive($inputArray, function($value,$key) { //walk each array in data structure
if(isset(value['id']) && isset($value['count'])) {
//we have found an entry with id and count:
if(!isset($idToCountArray[$value['id']])) {
//first count for id => create initial count
$idToCountArray[$value['id']] = intval($value['count']);
} else {
//n'th count for id => add count to sum
$idToCountArray[$value['id']] += intval($value['count']);
}
}
});
//build final structure:
$result = array();
foreach($idToCountArray as $id => $countSum) {
$result[] = array('id' => $id, 'count' => ''.$countSum);
}
Please note that I have not testet the code and there is probably a more elegant/performant solution.
You could use something like this:
$end_array = array();
function build_end_array($item, $key){
global $end_array;
if (is_array($item)){
if( isset($item["id"])){
if(isset($end_array[$item["id"]]))
$end_array[$item["id"]] = $end_array[$item["id"]] + $item["count"]*1;
else
$end_array[$item["id"]] = $item["count"]*1;
}
else {
array_walk($item, 'build_end_array');
}
}
}
array_walk($start_array, 'build_end_array');
Here is a fiddle.
Thank you ever so much everyone. I actually worked it by doing this: -
$fullArray = array_merge($live, $archive);
$array = array();
foreach($fullArray as $key=>$value) {
$id = $value['id'];
$array[$id][] = $value['count'];
}
$result = array();
foreach($array as $key=>$value) {
$result[] = array('id' => $key, 'count' => array_sum($value));
}
return $result;

Combine varied number of dynamically named arrays

I have seen the following: array_merge() How can I add a 'range' of an array name and the answers don't work for me.
I have an array that I am looping through in order to slice and convert certain currency strings to float numbers. I then have to array_merge them back together in order to work with the array and have been dynamically naming them so that I don't overwrite the previous array_merge. After doing so, I then need to combine all of the dynamically named arrays into one array.
Initially I had the following code, which worked great when I only had 3 nested arrays in the $order['product'] array. However, this number varies, and the code needs to do so as well.
$nr = 1;
foreach ($order['product'] as $product) {
$product_total = array_slice($product, 1);
array_walk($product_total, "convertCurrencyStringtoNumber");
${"final_product" . $nr} = array_merge($product, $product_total);
$nr++;
};
$arrays = array($final_product1, $final_product2, $final_product3);
var_dump($arrays);
This results in the following array:
array(3) {
[0]=> array(2) {
["source_code"]=> string(10) "408000-025"
["total"]=> float(18) }
[1]=> array(2) {
["source_code"]=> string(10) "408000-025"
["total"]=> float(17) }
[2]=> array(2) {
["source_code"]=> string(10) "408000-025"
["total"]=> float(2.75) } }
How do I implement a varied number of dynamically named arrays in the line:
$arrays = array($final_product1, $final_product2, $final_product3);
I attempted the following, but the array is nested incorrectly. Feel free to fix this code or come up with a better solution.
$nr = 1;
$i = 1;
foreach ($order['product'] as $product) {
$product_total = array_slice($product, 1);
array_walk($product_total, "convertCurrencyStringtoNumber");
${"final_product" . $nr} = array_merge($product, $product_total);
if ($nr > 0) {
$arrays = $final_product1;
for ($i = 2; $i <= $nr; $i++) {
$arrays = array_merge($arrays, ${"final_product" . $nr});
}
} else {
echo "There are no products in this order";
}
$nr++;
};
var_dump($arrays);
This results in the incorrectly nested array:
array(2) {
[0]=> array(2) {
[0]=> array(2) {
["source_code"]=> string(10) "408000-025"
["total"]=> float(18) }
[1]=> array(2) {
["source_code"]=> string(10) "408000-025"
["total"]=> float(17) } }
[1]=> array(2) {
["source_code"]=> string(10) "408000-025"
["total"]=> float(2.75) } }
Simply replace your dynamically single-named variables with an array:
$final_product = array();
foreach ($order['product'] as $product) {
$product_total = array_slice($product, 1);
array_walk($product_total, "convertCurrencyStringtoNumber");
$final_product[] = array_merge($product, $product_total);
};
var_dump($final_product);
Unless I'm missing something here... this should be as easy and simple as:
$final_array=[];
foreach ($order['product'] as $product) {
$final_array[]['total'] = (float) $product['whatever value 1 is...'];
$final_array[]['source_code'] = $product['source_code'];
}
var_dump($final_array);
If you need to apply convertCurrencyStringtoNumberbecause it does something weird to the variable then changethe seccond line to:
$final_array[]['total'] = convertCurrencyStringtoNumber(array_slice($product, 1));

php count+array_filter multiple values within a multi dimensional array [duplicate]

This question already has answers here:
array_count_values() with objects as values
(3 answers)
Closed 6 months ago.
How can I prevent duplicating the same block of code for each value that I want to search for?
I want to create a new array ($result) by counting for specific values within another multi-dimensional array ($data).
$result = array();
$result['Insulin'] = count(array_filter($data,function ($entry) {
return ($entry['choice'] == 'Insulin');
}
)
);
$result['TZD'] = count(array_filter($data,function ($entry) {
return ($entry['choice'] == 'TZD');
}
)
);
$result['SGLT-2'] = count(array_filter($data,function ($entry) {
return ($entry['choice'] == 'SGLT-2');
}
)
);
$data array example:
array(2) {
[0]=>
array(9) {
["breakout_id"]=>
string(1) "1"
["case_id"]=>
string(1) "1"
["stage_id"]=>
string(1) "1"
["chart_id"]=>
string(1) "1"
["user_id"]=>
string(2) "10"
["region"]=>
string(6) "Sweden"
["choice"]=>
string(7) "Insulin"
["switched_choice"]=>
NULL
["keep"]=>
string(1) "1"
}
[1]=>
array(9) {
["breakout_id"]=>
string(1) "1"
["case_id"]=>
string(1) "1"
["stage_id"]=>
string(1) "1"
["chart_id"]=>
string(1) "1"
["user_id"]=>
string(1) "7"
["region"]=>
string(6) "Sweden"
["choice"]=>
string(7) "Insulin"
["switched_choice"]=>
NULL
["keep"]=>
string(1) "1"
}
}
You may convert your anonymous function into a closure with the use keyword. Pass in a string variable for the value you want to match.
// Array of strings to match and use as output keys
$keys = array('Insulin','TZD','SGLT-2');
// Output array
$result = array();
// Loop over array of keys and call the count(array_filter())
// returning the result to $result[$key]
foreach ($keys as $key) {
// Pass $key to the closure
$result[$key] = count(array_filter($data,function ($entry) use ($key) {
return ($entry['choice'] == $key);
}));
}
Converting your var_dump() to an array and running this against it, the output is:
Array
(
[Insulin] => 2
[TZD] => 0
[SGLT-2] => 0
)
You can simplify it with array_count_values() as well:
$result2 = array_count_values(array_map(function($d) {
return $d['choice'];
}, $data));
print_r($result2);
Array
(
[Insulin] => 2
)
If you need zero counts for the missing ones, you may use array_merge():
// Start with an array of zeroed values
$desired = array('Insulin'=>0, 'TZD'=>0, 'SGLT-2'=>0);
// Merge it with the results from above
print_r(array_merge($desired, $result2));
Array
(
[Insulin] => 2
[TZD] => 0
[SGLT-2] => 0
)
Not the most efficient algorithm in terms of memory, but you can map each choice onto a new array and then use array_count_values():
$result = array_count_values(array_map(function($item) {
return $item['choice'];
}, $data));
Since 5.5 you can simplify it a little more by using array_column():
$result = array_count_values(array_column($data, 'choice'));
You can simplify your code easily if counting is your only goal :
$result = array();
foreach ($data AS $row) {
if (!isset($result[$row['choice']])) {
$result[$row['choice']] = 1;
} else {
$result[$row['choice']]++;
}
}
If you want to count only specific choices, you can change the above code into something like this :
$result = array();
$keys = array('Insulin', 'TZD', 'SGLT-2');
foreach ($data AS $row) {
if (!in_array($row['choice'], $keys)) {
continue;
}
if (!isset($result[$row['choice']])) {
$result[$row['choice']] = 1;
} else {
$result[$row['choice']]++;
}
}

Categories