remove duplicate array php - php

I have script like this
foreach ($onerow as $onekey => $dt ){
$arr = array();
foreach($row as $classkey => $classfoto):
$cek_class_foto = explode("/",$classfoto->name);
if($dt->foto_naam!=$cek_class_foto[1]){
$arr = array($dt->foto_naam);
print_r(array_unique($arr));
}
endforeach;
}
the output like this
Array ( [0] => _b101203.jpg )
Array ( [0] => _b101203.jpg )
my question is, how to remove this duplicates array?
Thank you

You are overwriting $arr for each iteration.
foreach ($onerow as $onekey => $dt ){
$arr = array();
foreach($row as $classkey => $classfoto):
$cek_class_foto = explode("/",$classfoto->name);
if($dt->foto_naam!=$cek_class_foto[1]){
$arr[] =$dt->foto_naam;
}
endforeach;
}
$arr = array_unique($arr);

$array1 = Array
(
'0' => Array
(
'messageId' => 9,
'userId' => 47,
'petId' => 68,
'message' => 'how hello',
'senderId' => 48,
'senderPetId' => 66,
'messageCreateTime' => '2015-07-31 11:44:59'
),
'1' => Array
(
'messageId' => 8,
'userId' => 49,
'petId' => 69,
'message' => 'pppppppppp',
'senderId' => 48,
'senderPetId' => 67,
'messageCreateTime' => '2015-07-31 11:15:16'
),
'2' => Array
(
'messageId' => 6,
'userId' => 48,
'petId' => 67,
'message' => 'gggg',
'senderId' => 49,
'senderPetId' => 69,
'messageCreateTime' => '2015-07-31 11:13:42'
),
'3' => Array
(
'messageId' => 2,
'userId' => 48,
'petId' => 67,
'message' => 'aaaaaaaa',
'senderId' => 47,
'senderPetId' => 68,
'messageCreateTime' => '2015-07-31 11:15:33'
)
);
/* code for removing last duplicate array within result array by KS */
/* matching between : userId, petId, senderId, senderPetId */
$temp_array = array();
$i = 0;
foreach($array1 as $key=>$value)
{
$FLAG = FALSE;
$temp_array = $array1[$key];
if($i==0)
{
$final_array[] = $temp_array;
}
else
{
for($j=0;$j<count($final_array);$j++)
{
if(($final_array[$j]['userId']==$temp_array['userId'] && $final_array[$j]['petId']==$temp_array['petId'] && $final_array[$j]['senderId']==$temp_array['senderId'] && $final_array[$j]['senderPetId']==$temp_array['senderPetId']) ||
($final_array[$j]['userId']==$temp_array['senderId'] && $final_array[$j]['petId']==$temp_array['senderPetId'] && $final_array[$j]['senderId']==$temp_array['userId'] && $final_array[$j]['senderPetId']==$temp_array['petId']))
{
$FLAG = TRUE;
}
}
if($FLAG == FALSE){
$final_array[] = $temp_array;
}
}
$i++;
}
print('<pre>');
print_r($final_array);
enter code here

Related

arrays with dif keys inside 1 array

like the question says, I have 2 foreach cycles, 1 cycle iterates an array with 4 keys, and the other one an array with 3 keys, how to get this two arrays in only 1 ?
I have this
....
],
],
'Detalle' => array()
];
foreach ($datos["line_items"] as $line => $item) {
$tempArray = array(
'NmbItem' => $item['name'],
'QtyItem' => $item['quantity'],
'PrcItem' => $item['price'],
'IndExe' => 1
);
}
foreach($datos["fee_lines"] as $line => $fee){
$tempArray=array(
'NmbItem' => $fee['name'],
'QtyItem' => 1,
'PrcItem' => $fee['total']
);
}
$dte['Detalle'][] = $tempArray;
}
if you notice the second array cycle doesnt contain 'indexe' key, after asign this tempArray in $dte['Detalle'][] = $tempArray only works with the last cycle, or the first one if I remove the second.
the output should be something like:
temp = Array (
array[0]
'NmbItem => name',
'QtyItem'=> 10,
'PrcItem'= 1000,
'IndExe' => 1
array[1]
'NmbItem => another name',
'QtyItem'=> 5,
'PrcItem'=> 3000
)
To make it work with your code, you should also add $dte['Detalle'][] = $tempArray; after the first loop.
The issue is that you are setting the $tempArray in each foreach so you end up with only the last one when assigning it in the $dte['Detalle'].
So, something like this should work:
foreach ($datos["line_items"] as $line => $item) {
$tempArray = array(
'NmbItem' => $item['name'],
'QtyItem' => $item['quantity'],
'PrcItem' => $item['price'],
'IndExe' => 1
);
}
$dte['Detalle'][] = $tempArray;
foreach($datos["fee_lines"] as $line => $fee){
$tempArray=array(
'NmbItem' => $fee['name'],
'QtyItem' => 1,
'PrcItem' => $fee['total']
);
}
$dte['Detalle'][] = $tempArray;
However, I would do it using the array_map function.
Docs for array_map
You can have it something like this:
<?php
$data_1 = array_map(function($item){
return array(
'NmbItem' => $item['name'],
'QtyItem' => $item['quantity'],
'PrcItem' => $item['price'],
'IndExe' => 1
);
}, $datos["line_items"]);
$data_2 = array_map(function($fee){
return array(
'NmbItem' => $fee['name'],
'QtyItem' => 1,
'PrcItem' => $fee['total']
)
}, $datos["fee_lines"]);
$dte['Detalle'] = array_merge($dte['Detalle'], $data_1, $data_2);

How can I achieve this in Array in PHP

am having problem achieving this result with array, I want to update another empty array with data in first array in such a way that the first two rows is ommitted and the first 3rows is added to the index 0 of the empty array, and the next 3 rows is also updated to the second index and so on. I have this Array in
`$arr = [
'tqty' => 9,
'tPrice' => 18700,
'food_name_1' => 'Black Coffee',
'food_quanty_1' => 1,
'food_price_1' => 1000,
'food_name_2' => 'Sub Combo',
'food_quanty_2' => 2,
'food_price_2' => 3000
];`
I want to use this array data and update another empty array this way, removing the first two rows
$arr2 = [
0 => [
'food_name_1' => 'Black Coffee',
'food_quanty_1' => 1,
'food_price_1' => 1000
],
1 => [
'food_name_2' => 'Sub Combo',
'food_quanty_2' => 2,
'food_price_2' => 3000
]
];
here is my code so far
$arr = [
'tqty' => 9,
'tPrice' => 18700,
'food_name_1' => 'Black Coffee',
'food_quanty_1' => 1,
'food_price_1' => 1000,
'food_name_2' => 'Sub Combo',
'food_quanty_2' => 2,
'food_price_2' => 3000
];
$newdat = [];
$count = 0;
$oldcount = 1;
foreach($arr as $key => $value){
if(preg_match_all('!\d+!', $key, $matches)){
if($oldcount == $matches[0][0]){
$newdat[$matches[0][0]] = [
$count => [
$key => $value
]
];
} else{
$count = 0;
$oldcount = $matches[0][0];
}
}
$count++;
}
I hope I get help soon. thanks
Assuming the array keys and order stay consistent you could use array_chunk
<?php
$inArray = [
'tqty' => 9,
'tPrice' => 18700,
'food_name_1' => 'Black Coffee',
'food_quanty_1' => 1,
'food_price_1' => 1000,
'food_name_2' => 'Sub Combo',
'food_quanty_2' => 2,
'food_price_2' => 3000,
];
$outArray = [];
// Remove first 2 values.
$inArray = array_slice( $inArray, 2 );
// 'Chunk' the rest of the values.
// true preserves keys.
$outArray = array_chunk( $inArray, 3, true );
echo '<pre>' . print_r( $outArray, true ) . '</pre>';
/**
Output:
<pre>Array
(
[0] => Array
(
[food_name_1] => Black Coffee
[food_quanty_1] => 1
[food_price_1] => 1000
)
[1] => Array
(
[food_name_2] => Sub Combo
[food_quanty_2] => 2
[food_price_2] => 3000
)
)
</pre>
*/
If I have understood you correctly,
$newdata = array();
for ($i = 1; $i++;) { // Intentionally no condition set.
if (array_key_exists('food_name_' . $i, $arr)) {
$temparray = array();
$temparray['food_name_' . $i] = $arr['food_name_' . $i];
if (array_key_exists('food_quanty_' . $i, $arr)) {
$temparray['food_quanty_' . $i] = $arr['food_quanty_' . $i];
}
if (array_key_exists('food_price_' . $i, $arr)) {
$temparray['food_price_' . $i] = $arr['food_price_' . $i];
}
$newdata[] = $temparray;
} else {
break; // break out of the loop
}
}
echo "<pre>";
print_r($newdata);
echo "</pre>";
die();
Loop through it and build the array index string via variables.
<?php
$arr = [
'tqty' => 9,
'tPrice' => 18700,
'food_name_1' => 'Black Coffee',
'food_quanty_1' => 1,
'food_price_1' => 1000,
'food_name_2' => 'Sub Combo',
'food_quanty_2' => 2,
'food_price_2' => 3000
];
foreach(array("food_name_","food_quanty_","food_price_") as $v){
// replace the set value of 2 here with a count() on the $arr
// and some basic math - IF you are always sure you'll have 3 fields
for($i=0;$i<2;$i++){
$newarr[$i][$v.($i+1)]=$arr[$v.($i+1)];
}
}
print_r($newarr);
?>
Here's a solution that will locate the _x at the end to check its a digit
This solution does not worry about how many non numbered fields you have, or how many fields there are per numbered "row", they are also indexed based on the _x number.
$arr = [
'tqty' => 9,
'tPrice' => 18700,
'food_name_1' => 'Black Coffee',
'food_quanty_1' => 1,
'food_price_1' => 1000,
'food_name_2' => 'Sub Combo',
'food_quanty_2' => 2,
'food_price_2' => 3000
];
$arr2 = array();
foreach( $arr as $key => $value )
{
$explode = explode( '_', $key );
if( ctype_digit( $index = end( $explode ) ) === true)
{
if( isset( $arr2[ $index ] ) === false )
{
$arr2[ $index ] = array();
}
$arr2[ $index ][ substr( $key, 0, strlen( $key ) - 1 - strlen( $index ) ) ] = $value;
}
}
print_r( $arr2 );
Output:
Array
(
[1] => Array
(
[food_name] => Black Coffee
[food_quanty] => 1
[food_price] => 1000
)
[2] => Array
(
[food_name] => Sub Combo
[food_quanty] => 2
[food_price] => 3000
)
)
If you already know that you need always the same indexes from $arr, you can use the array_keys function in order to index the associative array.
Example:
$keys = array_keys($arr);
echo '<br><br>'.$arr[$keys[1]];
Here is a complete example:
$keys = array_keys($arr); #stores the associative keys by index
$arr2 = array();
/* For each array $arr do the following */
$limit = 5; #substitute this with: count($arraylist)
for( $n_array=0; $n_array<limit; $n_array++ ){
$cur_arr = array(); #substitute with your: $arraylist[ $n_array ]
for( $a = 2; $a<count($arr); $a++ ){
$cur_arr[ $keys[$a] ] = $arr[ $keys[$a] ];
}
$arr2[ $n_array ] = $cur_arr;
}
Hope it will be helpful

how to calculate the sum of same array values in PHP

I have an array like this
$estimate[0]=>
'gear' =>'MMG'
'total' => 315
'efforts' => 9
'afh' => 18
$estimate[1]=>
'gear' =>'MMG'
'total' => 400
'efforts' => 2
'afh' => 6
$estimate[2]=>
'gear' =>'BOO'
'total' => 200
'efforts' => 20
'afh' => 16
$estimate[3]=>
'gear' =>'BOB'
'total' => 250
'efforts' => 20
'afh' => 16
I want to calculate the sum of total, efforts and afh in which gear is same and it will be stored in the another array. Following my coding is working when the array (estimate) size is less than 5.
$calculate = array();
for($et=0;$et<count($estimate);):
if($et==0):
$calculate[$et]['gear'] = $estimate[$et]['gear'];
$calculate[$et]['total'] = $estimate[$et]['total'];
$calculate[$et]['efforts'] = $estimate[$et]['efforts'];
$calculate[$et]['afh'] = $estimate[$et]['afh'];
goto loopend;
endif;
for($cet=0;$cet<count($calculate);$cet++):
if($estimate[$et]['gear'] == $calculate[$cet]['gear']):
$calculate[$cet]['total'] = $calculate[$cet]['total'] + $estimate[$et]['total'];
$calculate[$cet]['efforts'] = $calculate[$cet]['efforts'] + $estimate[$et]['efforts'];
$calculate[$cet]['afh'] = $calculate[$cet]['afh'] + $estimate[$et]['afh'];
goto loopend;
endif;
endfor;
$calculate[$et]['gear'] = $estimate[$et]['gear'];
$calculate[$et]['total'] = $estimate[$et]['total'];
$calculate[$et]['efforts'] = $estimate[$et]['efforts'];
$calculate[$et]['afh'] = $estimate[$et]['afh'];
goto loopend;
loopend:$et++;
endfor;
The coding is not working more than many gears. Sometimes it works. I can't find the issues. Please help me to solve the issues.
You might use array_reduce:
$result = array_reduce($estimate, function($carry, $item) {
if (!isset($carry[$item["gear"]])) {
$carry[$item["gear"]] = $item;
return $carry;
}
$carry[$item["gear"]]["total"] += $item["total"];
$carry[$item["gear"]]["efforts"] += $item["efforts"];
$carry[$item["gear"]]["afh"] += $item["afh"];
return $carry;
});
Demo
As per my comment use foreach loop when your array length is not define
Here is your desired code
<?php
$estimate = array(
"0" => array (
"gear" => 35,
"total" => 30,
"efforts" => 39,
"afh" => 39,
),
"1" => array (
"gear" => 35,
"total" => 30,
"efforts" => 39,
"afh" => 39,
),
"2" => array (
"gear" => 35,
"total" => 30,
"efforts" => 39,
"afh" => 39,
),
);
$gear=0;
$total=0;
$efforts=0;
$afh=0;
foreach ($estimate as $key => $value) {
$gear=$gear+$value['gear'];
$total=$gear+$value['total'];
$efforts=$gear+$value['efforts'];
$afh=$gear+$value['afh'];
}
echo "<pre>";
$result = array('gear' => $gear, 'total' => $total,'efforts' => $efforts,'afh' => $afh);
echo "<pre>";
print_r($result);
you can check the result HERE
<?php
$new_arr = array();
$estimate[0] =array(
'gear' =>'MMG',
'total' => 315,
'efforts' => 9,
'afh' => 18
);
$estimate[1]=array(
'gear' =>'MMG',
'total' => 400,
'efforts' => 2,
'afh' => 6,
);
$estimate[2]=array(
'gear' =>'BOO',
'total' => 200,
'efforts' => 20,
'afh' => 16,
);
$estimate[3]=array(
'gear' =>'BOB',
'total' => 250,
'efforts' => 20,
'afh' => 16,
);
foreach ($estimate as $key => $value) {
$new_arr[$value['gear']] = array(
'total' => (isset($new_arr[$value['gear']]['total']) ? ($new_arr[$value['gear']]['total'] + $value['total']) : $value['total'] ),
'efforts' => (isset($new_arr[$value['gear']]['efforts']) ? ($new_arr[$value['gear']]['efforts'] + $value['efforts']) : $value['efforts'] ),
'afh' => (isset($new_arr[$value['gear']]['afh']) ? ($new_arr[$value['gear']]['afh'] + $value['afh']) : $value['afh'] )
);
}
echo "<pre>";print_r($new_arr);

Recursive function to build an array

Can anyone see why this isn't working?
private static function traverseTree($tree,$node)
{
$nodes = array();
$results = array();
$children = $tree->where('parent_id',$node->id)->where('type',UserGroup::DEPARTMENT_TYPE);
foreach($children as $child){
$nodes[] = $child->id;
$children = self::traverseTree($tree,$child);
$results = array_merge ($nodes,$children);
}
return $results;
}
I am stepping through it and I can see that the children are getting found but they are not included in the final results.
The final results just contain the top level.
Detail added:
$tree is a Laravel Collection, if I pipe this to an array I get:
array (
0 =>
array (
'id' => 21,
'name' => 'Top',
'type' => 1,
'parent_id' => 0,
),
1 =>
array (
'id' => 33,
'name' => 'UKDept',
'type' => 2,
'parent_id' => 21,
),
2 =>
array (
'id' => 36,
'name' => 'UKSubDept',
'parent_id' => 33,
),
3 =>
array (
'id' => 37,
'name' => 'USDept',
'type' => 2,
'parent_id' => 21,
),
)
$node:
array (
'id' => 21,
'name' => 'Top',
'type' => 1,
'parent_id' => 0,
),
The first call to populate $children gives:
array (
0 =>
array (
'id' => 33,
'name' => 'UKDept',
'type' => 2,
'parent_id' => 21,
),
1 =>
array (
'id' => 37,
'name' => 'USDept',
'type' => 2,
'parent_id' => 21,
),
)
Try taking the array outside the function.
$nodes = array();
$results = array();
private static function traverseTree($tree,$node)
{
$children = $tree->where('parent_id',$node->id)->where('type',UserGroup::DEPARTMENT_TYPE);
foreach($children as $child){
$nodes[] = $child->id;
$children = self::traverseTree($tree,$child);
$results = array_merge ($nodes,$children);
}
return $results;
}
It will not reinitialize them each time you call the function.Check if it works?
Looks like $child is an array but you are treating it like an object. Try changing:
$nodes[] = $child->id;
to
$nodes[] = $child['id'];
I have this working now, one stupid mistake I made was:
foreach($children as $child){
$nodes[] = $child->id;
$children = self::traverseTree($tree,$child);
$results = array_merge ($nodes,$children);
Using $children as a variable name twice!
This is the complete function:
private static function traverseTree($tree,$node)
{
$initialId = array();
$results = array();
$results[] = $node->id;
$children = $tree->where('parent_id',$node->id);
foreach($children as $node){
//if this is a department, then we need to go deeper
if($node->type == DEPARTMENT) {
$nodesChildren = self::traverseTree($tree, $node);
$results = array_merge ($results,$nodesChildren);
}else{
//just add this node to the results array
$results[] = $node->id;
}
}
return $results;
}

how to find a element in a nested array and get its sub array index

when searching an element in a nested array, could i get back it's 1st level nesting index.
<?php
static $cnt = 0;
$name = 'victor';
$coll = array(
'dep1' => array(
'fy' => array('john', 'johnny', 'victor'),
'sy' => array('david', 'arthur'),
'ty' => array('sam', 'joe', 'victor')
),
'dep2' => array(
'fy' => array('natalie', 'linda', 'molly'),
'sy' => array('katie', 'helen', 'sam', 'ravi', 'vipul'),
'ty' => array('sharon', 'julia', 'maddy')
)
);
function recursive_search(&$v, $k, $search_query){
global $cnt;
if($v == $search_query){
/* i want the sub array index to be returned */
}
}
?>
i.e to say, if i'am searching 'victor', i would like to have 'dep1' as the return value.
Could anyone help ??
Try:
$name = 'victor';
$coll = array(
'dep1' => array(
'fy' => array('john', 'johnny', 'victor'),
'sy' => array('david', 'arthur'),
'ty' => array('sam', 'joe', 'victor')
),
'dep2' => array(
'fy' => array('natalie', 'linda', 'molly'),
'sy' => array('katie', 'helen', 'sam', 'ravi', 'vipul'),
'ty' => array('sharon', 'julia', 'maddy')
)
);
$iter = new RecursiveIteratorIterator(new RecursiveArrayIterator($coll), RecursiveIteratorIterator::SELF_FIRST);
/* These will be used to keep a record of the
current parent element it's accessing the childs of */
$parent_index = 0;
$parent = '';
$parent_keys = array_keys($coll); //getting the first level keys like dep1,dep2
$size = sizeof($parent_keys);
$flag=0; //to check if value has been found
foreach ($iter as $k=>$val) {
//if dep1 matches, record it until it shifts to dep2
if($k === $parent_keys[$parent_index]){
$parent = $k;
//making sure the counter is not incremented
//more than the number of elements present
($parent_index<$size-1)?$parent_index++:'';
}
if ($val == $name) {
//if the value is found, set flag and break the loop
$flag = 1;
break;
}
}
($flag==0)?$parent='':''; //this means the search string could not be found
echo 'Key = '.$parent;
Demo
This works , but I don't know if you are ok with this...
<?php
$name = 'linda';
$col1=array ( 'dep1' => array ( 'fy' => array ( 0 => 'john', 1 => 'johnny', 2 => 'victor', ), 'sy' => array ( 0 => 'david', 1 => 'arthur', ), 'ty' => array ( 0 => 'sam', 1 => 'joe', 2 => 'victor', ), ), 'dep2' => array ( 'fy' => array ( 0 => 'natalie', 1 => 'linda', 2 => 'molly', ), 'sy' => array ( 0 => 'katie', 1 => 'helen', 2 => 'sam', 3 => 'ravi', 4 => 'vipul', ), 'ty' => array ( 0 => 'sharon', 1 => 'julia', 2 => 'maddy', ), ), );
foreach($col2 as $k=>$arr)
{
foreach($arr as $k1=>$arr2)
{
if(in_array($name,$arr2))
{
echo $k;
break;
}
}
}
OUTPUT :
dept2
Demo

Categories