Related
I will try to explain my problem in small examples:
I have a multidimensional array that represents data from the database, lets's say the input looks like this:
Array
(
[0] => Array
(
[groupRange] => 20-25
[value] => 12
[followersFemaleRate] => 12
[followersMaleRate] => 14
)
[1] => Array
(
[groupRange] => 30-44
[value] => 32
[followersFemaleRate] => 17
[followersMaleRate] => 3
)
[2] => Array
(
[groupRange] => 30-44
[value] => 88
[followersFemaleRate] => 17
[followersMaleRate] => 3
)
)
What I want? To sum value, followersFemaleRate, followersMaleRate with the same groupRange, so the output should be this:
Array
(
[0] => Array
(
[groupRange] => 20-25
[value] => 12
[followersFemaleRate] => 12
[followersMaleRate] => 14
)
[1] => Array
(
[groupRange] => 30-44
[value] => 120
[followersFemaleRate] => 34
[followersMaleRate] => 6
)
)
My code:
$RangeArray = [];
foreach($dbProfile->getData() as $d) {
foreach ($d->getGroupPercentages() as $x){
$ageRangeSingleArray['groupRange'] = $x->getGroupRange();
$ageRangeSingleArray['value'] = $x->getValue();
$ageRangeSingleArray['followersFemaleRate'] = $x->getFollowerGenderFemale();
$ageRangeSingleArray['followersMaleRate'] = $x->getFollowerGenderMale();
$RangeArray [] = $ageRangeSingleArray;
}
}
However im stuck, my idea is to first check if groupRage already exists, if yes, sum values for that range, if not add new element groupRange with values, any help with code?
#Salines solution was good, but I offer a simple solution for the beginners...
Another simple solution to your problem:
$input = [
[
'groupRange' => '20-25',
'value' => 12,
'followersFemaleRate' => 12,
'followersMaleRate' => 14,
],
[
'groupRange' => '30-44',
'value' => 88,
'followersFemaleRate' => 17,
'followersMaleRate' => 3,
],
[
'groupRange' => '30-44',
'value' => 32,
'followersFemaleRate' => 17,
'followersMaleRate' => 3,
],
];
$groupRangeHolder = [];
$output = [];
foreach($input as $item) {
if( ! array_key_exists( $item['groupRange'] , $groupRangeHolder ) )
{
$groupRangeHolder[$item['groupRange']]['value'] = $item['value'];
$groupRangeHolder[$item['groupRange']]['followersFemaleRate'] = $item['followersFemaleRate'];
$groupRangeHolder[$item['groupRange']]['followersMaleRate'] = $item['followersMaleRate'];
}
else
{
$groupRangeHolder[$item['groupRange']]['value'] += $item['value'];
$groupRangeHolder[$item['groupRange']]['followersFemaleRate'] += $item['followersFemaleRate'];
$groupRangeHolder[$item['groupRange']]['followersMaleRate'] += $item['followersMaleRate'];
}
}
$cur = 0;
foreach($groupRangeHolder as $key => $values)
{
$output[$cur]['groupRange'] = $key;
$output[$cur]['value'] = $values['value'];
$output[$cur]['followersFemaleRate'] = $values['followersFemaleRate'];
$output[$cur++]['followersMaleRate'] = $values['followersMaleRate'];
}
echo "<pre>";
print_r($output);
echo "</pre>";
try:
$input = [
[
'groupRange' => '20-25',
'value' => 12,
'followersFemaleRate' => 12,
'followersMaleRate' => 14,
],
[
'groupRange' => '30-44',
'value' => 88,
'followersFemaleRate' => 17,
'followersMaleRate' => 3,
],
[
'groupRange' => '30-44',
'value' => 32,
'followersFemaleRate' => 17,
'followersMaleRate' => 3,
],
];
$groupedArray = [];
foreach( $input as $item ){
$groupedArray[$item['groupRange']]['groupRange'] = $item['groupRange'];
$groupedArray[$item['groupRange']]['value'] = ($groupedArray[$item['groupRange']]['value'] ?? 0) + $item['value'];
$groupedArray[$item['groupRange']]['followersFemaleRate'] = $item['followersFemaleRate'];
$groupedArray[$item['groupRange']]['followersMaleRate'] = $item['followersMaleRate'];
}
$output = array_values($groupedArray);
print_r($output);
output:
Array
(
[0] => Array
(
[groupRange] => 20-25
[value] => 12
[followersFemaleRate] => 12
[followersMaleRate] => 14
)
[1] => Array
(
[groupRange] => 30-44
[value] => 120
[followersFemaleRate] => 17
[followersMaleRate] => 3
)
)
I working on a function which filters a multi dimensional array, if the successive arrays have same value, I need to remove the arrays in between and get only the first and last of the successive arrays with duplicate values.
I cant figure out how to do this.
Hope you can help me.
Thanks.
SAMPLE CODE
function removeDuplicates($array){
$result = [];
$count = 0;
$firstValue = null;
for ($i = 0; $i < count($array); $i++) {
if($array[$i]['id'] == firstValue){
$result[] = $array[$i]);
}else{
// do action
}
}
return $array;
}
Sample Array
Array (
[0] => Array (
[key] => 0
[value] => 25
)
[1] => Array (
[key] => 1
[value] => 25
)
[2] => Array (
[key] => 2
[value] => 25
)
[3] => Array (
[key] => 3
[value] => 33
)
[4] => Array (
[key] => 4
[value] => 45
)
[5] => Array (
[key] => 5
[value] => 66
)
[6] => Array (
[key] => 6
[value] => 66
)
[7] => Array (
[key] => 7
[value] => 66
)
[8] => Array (
[key] => 8
[value] => 66
)
[9] => Array (
[key] => 9
[value] => 55
)
)
Here the first 3 arrays have same values (25), I need to remove the 2nd array and retain the 1st and 3rd, also with the 6th to 9th only retain the 6th and 9th array.
Expected Result
Array (
[0] => Array (
[key] => 0
[value] => 25
)
[2] => Array (
[key] => 2
[value] => 25
)
[3] => Array (
[key] => 3
[value] => 33
)
[4] => Array (
[key] => 4
[value] => 45
)
[5] => Array (
[key] => 5
[value] => 66
)
[8] => Array (
[key] => 8
[value] => 66
)
[9] => Array (
[key] => 9
[value] => 55
)
)
Try this:
$array = [
["key" => 0, "value" => 25],
["key" => 1, "value" => 25],
["key" => 2, "value" => 25],
["key" => 3, "value" => 33],
["key" => 4, "value" => 45],
["key" => 5, "value" => 66],
["key" => 6, "value" => 66],
["key" => 7, "value" => 66],
["key" => 8, "value" => 66],
["key" => 9, "value" => 55],
];
for ($i = 0; $i < count($array); $i++) {
if (!isset($array[$i])){
continue;
}
if ($array[$i]['value'] == $array[$i+1]['value']) {
$j = 1;
while ($array[$i]['value'] == $array[$i+$j+1]['value']) {
unset($array[$i+$j]);
$j += 1;
}
}
}
print_r($array);
Since you need to preserve the keys, for loop will throw a notice when an element is not set. This is why we first check if an element exists.
Then the loop looks for two identical values that are consecutive i.e. $i and $i+1. Once it finds them, it enters a while loop to test for 3 or more consecutive identical values. It will only unset a consecutive item if there is at least one occurrence before it and one after it. For example, it will delete $i+2 only if $i+3 is identical.
Hope this helps!
You can approach this as
$r = [];
$lastKey = '';
foreach($array as $k => $v){
if(in_array($v['value'], array_column($r, 'value'))){
$lastKey = $v['key'];
}else{
if($lastKey && !in_array($lastKey, array_column($r, 'key'))){
end($r);
$r[] = [ 'key' => $lastKey, 'value' => $r[key($r)]['value']];
}
$r[] = [ 'key' => $v['key'] , 'value' => $v['value'] ];
$lastKey = $v['key'];
}
}
https://3v4l.org/f6FQv
Here is the solution:
Your array is something like this:
$array = [
["key" => 0, "value" => 25],
["key" => 1, "value" => 25],
["key" => 2, "value" => 25],
["key" => 3, "value" => 33],
["key" => 4, "value" => 45],
["key" => 5, "value" => 66],
["key" => 6, "value" => 66],
["key" => 7, "value" => 66],
["key" => 8, "value" => 66],
["key" => 9, "value" => 55],
];
first, find the first and last occurrence of each value.
You need a method that travels through the array and find the exact value.
Look at this:
function search($search, $array)
{
foreach ($array as $key => $val) {
if ($val['value'] === $search) {
return $key;
}
}
return null;
}
Running $firstOccurrence = search(25, $array) will find the first occurrence of 25.
Now, for finding the index of the last occurrence, we should reverse array to traveling from the end of the array. So $lastOccurrence = search(25, array_reverse($array, true)) will find last occurrence index of 25.
Ok, When we process each value, so, We should not process it again. So we need an array which will hold values which are processed.
Final Code:
function testArray()
{
$array = [
["key" => 0, "value" => 25],
["key" => 1, "value" => 25],
["key" => 2, "value" => 25],
["key" => 3, "value" => 33],
["key" => 4, "value" => 45],
["key" => 5, "value" => 66],
["key" => 6, "value" => 66],
["key" => 7, "value" => 66],
["key" => 8, "value" => 66],
["key" => 9, "value" => 55],
];
$processedItems = [];
$newArray = [];
foreach ($array as $index => $item) {
if (in_array($item["value"], $processedItems))
continue;
$processedItems[] = $item["value"];
$firstIndex = search($item["value"], $array);
$lastIndex = search($item["value"], array_reverse($array, true));
$newArray[$firstIndex] = $array[$firstIndex];
if ($firstIndex != $lastIndex)
$newArray[$lastIndex] = $array[$lastIndex];
}
print_r($newArray);
}
function search($search, $array)
{
foreach ($array as $key => $val) {
if ($val['value'] === $search) {
return $key;
}
}
return null;
}
Please try this hope it's work
for ($i = 0; $i < count($array); $i++) {
if ($array[$i]['value'] == $array[$i+1]['value']) {
$j = 1;
while ($array[$i]['value'] == $array[$i+$j+1]['value']) {
echo $array[$i]['value'].'==='.$array[$i+$j+1]['value'];
unset($array[$i+$j]);
$j += 1;
}
}
}
This is my array:
Array (
[0] => Array ( [SocketID] => 1 [SocketName] => Name [SocketDecimal] => 0 [SocketHex] => 00 [SocketAtt] => 1 [Category] => 1 [Value] => 100 [Procentage] => 0 )
[1] => Array ( [SocketID] => 2 [SocketName] => Name2 [SocketDecimal] => 50 [SocketHex] => 32 [SocketAtt] => 1 [Category] => 1 [Value] => 800 [Procentage] => 0 )
[2] => Array ( [SocketID] => 3 [SocketName] => Name3 [SocketDecimal] => 100 [SocketHex] => 64 [SocketAtt] => 1 [Category] => 1 [Value] => 60 [Procentage] => 0 )
)
How can I extract a row by SocketDecimal?
For example: I want to extract row where SocketDecimal = 50 and make new an array only with that row.
foreach($array as $entry) {
if($entry['SocketDecimal'] == 50)
$newArr[] = $entry;
}
$newArr will contain the desired "row". Of course you can manipulate the if-statement depending on which "row" (I'd just call it array entry) you want to extract.
It's not the best way for big data! It's easy for deep multiarrays.
$arr = array(
array('socket_id'=>1,'name'=>'test1'),
array('socket_id'=>2,'name'=>'test2'),
array('socket_id'=>3,'name'=>'test3'),
array('socket_id'=>2,'name'=>'test4')
);
$newArr = array();
foreach($arr as $row){
foreach($row as $key=>$r){
if($key == 'socket_id' && $r==2)
$newArr[] = $row;
}
}
print_r($newArr);
$result = array();
foreach($input as $i){
if($i['SocketDecimal']==50)
$result[]=$i;
}
You can do it by this method
foreach ($yourarray as $key => $value){
$newarray = array("SocketDecimal"=>$value["SocketDecimal"];
}
print_r($newarray);
If your result array is like given below
$arr = array(
array( 'SocketID' => 1, 'SocketName' => 'Name', 'SocketDecimal' => 0, 'SocketHex' => 0, 'SocketAtt' => 1, 'Category' => 1, 'Value' => 100, 'Procentage' => 0 ),
array ( 'SocketID' => 2, 'SocketName' => 'Name2', 'SocketDecimal' => 50, 'SocketHex' => 32, 'SocketAtt' => 1, 'Category' => 1, 'Value' => 800, 'Procentage' => 0 ),
array ( 'SocketID' => 3, 'SocketName' => 'Name3', 'SocketDecimal' => 100, 'SocketHex' => 64, 'SocketAtt' => 1, 'Category' => 1, 'Value' => 60, 'Procentage' => 0 )
);
print_r($arr);
Get row for SocketDecimal=50 by following loop:
<pre>
$resultArr = '';
foreach($arr as $recordSet)
{
if($recordSet['SocketDecimal'] == 50)
{
$resultArr[] = $recordSet;
break;
}
}
</pre>
print_r($resultArr);
break foreach loop so that it will not traverse for all the array when SocketDecimal(50) founded.
You can use array_column + array_search combo
$array = Array (
"0" => Array ( "SocketID" => 1, "SocketName" => "Name", "SocketDecimal" => 0, "SocketHex" => 00, "SocketAtt" => 1, "Category" => 1, "Value" => 100, "Procentage" => 0 ) ,
"1" => Array ( "SocketID" => 2, "SocketName" => "Name2", "SocketDecimal" => 50, "SocketHex" => 32, "SocketAtt" => 1, "Category" => 1, "Value" => 800, "Procentage" => 0 ),
"2" => Array ( "SocketID" => 3, "SocketName" => "Name3", "SocketDecimal" => 100, "SocketHex" => 64, "SocketAtt" => 1, "Category" => 1, "Value" => 60 ,"Procentage" => 0 )
);
var_dump($array[array_search(50,array_column($array,'SocketDecimal'))]);
I have two arrays, examples of the structures below:
Array #1 -- keys are stored in the first index of the array as the corresponding value.
Array(
[0] => Array(
[0] => name
[1] => time
),
[1] => Array(
[0] => Bob
[1] => 20
),
[2] => Array(
[0] => Jack
[1] => 25
)
)
Array #2 -- each array has a numbered key and named key with the corresponding value being the same
Array(
[0] => Array(
[name] => Bob
[0] => Bob
[time] => 20
[1] => 20
),
[1] => Array(
[name] => Test
[0] => Test
[time] => 40
[1] => 40
)
)
Attempt:
foreach($arr as $record) {
if(!in_array($record['name'], $names))
$names[] = $record['name'];
}
foreach($csv as $rec) {
if(!in_array($rec[0], $names))
$names[] = $rec[0];
}
How can I combine these arrays, and weed out and duplicates based on the value of the name?
Try the code below, i added commands between the code.
//Array 1
$array1 = Array(
0 => Array(
0 => "Bob",
1 => 20,
),
1 => Array(
0 => "Jack",
1 => 25,
));
//Array 2
$array2 = Array(
0 => Array(
"name" => "Bob",
0 => "Bob",
"time" => 20,
1 => 20,
),
1 => Array(
"name" => "Test",
0 => "Test",
"time" => 40,
1 => 40,
));
//Function to search if the value already exists
function inArray($array, $search)
{
foreach($array as $key=>$subArray)
{
if(in_array($search, $subArray))
{
return true;
}
}
return false;
}
$newArray = array();
//Loop over array1 length + array2 length
for($i = 0 ; $i < (count($array1) + count($array2)) ; $i++)
{
//Choose the array based on the counter ($i)
if($i < count($array1))
{
$data = $array1;
$arrayIndex = $i;
}
else
{
$data = $array2;
$arrayIndex = $i - count($array1);
}
//Check if array value exists
if(!inArray($newArray,$data[$arrayIndex][0]))
{
//Add if it doesn't exists with the keys 'name' and 'time'
$newArray[] = array('name' => $data[$arrayIndex][0], 'time'=> $data[$arrayIndex][1]);
}
}
print_r($newArray);
The output will be:
Array
(
[0] => Array
(
[name] => Bob
[time] => 20
)
[1] => Array
(
[name] => Jack
[time] => 25
)
[2] => Array
(
[name] => Test
[time] => 40
)
)
I have this code that outputs something like:
Array (
[0] => 15
[1] => 13
[2] => 16
[3] => 16
[4] => 10
[5] => 10
[6] => 13
[7] => 13
)
But, i want this structure:
Array (
[0] => Array ( [0] => 15, [1] => 13, [2] => 16, [3] => 16)
[0] => Array ( [0] => 10, [1] => 10, [2] => 13, [3] => 13)
)
This didn't solve : $score[] = array($score_bd);. Any idea ?
php code
$i =0;
foreach ($arr_user_apply as $val) {
$new_val = array($val);
$arr[$i] = array_merge($str, $new_arr_tags_ids, $new_val, $new_id_oferta);
$sql = $db -> prepare("
query
"
);
call_user_func_array(array($sql, "bind_param"), $arr[$i]);
$sql -> execute();
$sql -> bind_result($score_bd);
while ($sql -> fetch()) {
$score[] = $score_bd;
};
$i++;
}
If you're just trying to add another dimension to your first array by placing the key value of the key into the new array something like this might work:
$firstArray = Array ( 0 => 15, 1 => 15, 2 => 13, 3 => 13, 4 => 16, 5 => 16, 6 => 10, 7 => 10, 8 => 13, 9 => 13, 10 => 6, 11 => 6 );
$newArray = Array();
foreach($firstArray as $key => $value)
{
$newArray[] = Array($key => Array($value));
}
echo "<pre>";
print_r($newArray);
echo "</pre>";
EDIT:
if that's one dimension too deep, then just try this:
$firstArray = Array ( 0 => 15, 1 => 15, 2 => 13, 3 => 13, 4 => 16, 5 => 16, 6 => 10, 7 => 10, 8 => 13, 9 => 13, 10 => 6, 11 => 6 );
$newArray = Array();
foreach($firstArray as $key => $value)
{
$newArray[$key] = Array($value);
}
echo "<pre>";
print_r($newArray);
echo "</pre>";
$arr = array ( 0 => 15 ,1 => 15, 2 => 13, 3 => 13 ,4 => 16 ,5 => 16 ,6 => 10, 7 => 10);
foreach($arr as $key=>$value){
$new_arr[$key][0] = $value;
}
i am not sure if the question is clear, but this works properly to me
$score = array();
while ($sql -> fetch()) {
$score[] = $score_bd;
};
$new_score[] = array($score);
Array (
[0] => Array ( [0] => Array ( [0] => 15 [1] => 13 [2] => 16 ) )
[1] => Array ( [0] => Array ( [0] => 10 [1] => 13 [2] => 6 ) )
)