concat array values, if contains duplicates - php - php

This is my array. And i need to concat array values if duplicate exists.
Array
(
[0] => Array
(
[id] => 3
[location_id] => 2
[location_name] => 1st Floor
[type] => 1
)
[1] => Array
(
[id] => 6
[location_id] => 2
[location_name] => 1st Floor
[type] => 1
)
[2] => Array
(
[id] => 7
[location_id] => 1
[location_name] => Ground Floor
[type] => 1
)
)
And below is my code, which doesn't concat on unique values.
$conct= array();
foreach ($myArray as $array)
{
foreach ($array as $key => $value)
{
if ( ! isset($merged[$key]))
{
$conct[$key] = $value;
}
else
{
$conct[$key] .= ",".$value;
}
}
}
This is giving me.
Array
(
[0] => Array
(
[id] => 3,6,7
[location_id] => 2,2,1
[location_name] => 1st Floor,1st Floor,Ground Floor
[type] => 1,1,1
)
)
And i need to concat the values based on unique location_id and location_name.
My result array should be.
Array
(
[0] => Array
(
[id] => 3,6
[location_id] => 2,2
[location_name] => 1st Floor,1st Floor
[type] => 1,1
)
[1] => Array
(
[id] => 7
[location_id] => 1
[location_name] => Ground Floor
[type] => 1
)
)
How to achieve this?

Try this..
<?php
$new_values = array();
$values = array(
array('id'=> 1, 'location_id' => 2, 'location_name' => '1st Floor','type'=>1),
array('id'=> 6, 'location_id' => 2, 'location_name' => '1st Floor','type'=>1),
array('id'=> 7, 'location_id' => 1, 'location_name' => 'Gound Floor','type'=>1),
);
foreach($values as $value) {
if(isset($new_values[$value['location_id']])) {
$temp = $new_values[$value['location_id']];
$temp['id'] .= ',' . $value['id'];
$temp['location_id'] .= ',' . $value['location_id'];
$temp['location_name'] .= ',' . $value['location_name'];
$temp['type'] .= ',' . $value['type'];
$new_values[$value['location_id']] = $temp;
} else {
$new_values[$value['location_id']] = $value;
}
}
$new_values = array_values($new_values);
print_r($new_values);
?>
Output:Array ( [0] => Array ( [id] => 1,6 [location_id] => 2,2 [location_name] => 1st Floor,1st Floor [type] => 1,1 ) [1] => Array ( [id] => 7 [location_id] => 1 [location_name] => Gound Floor [type] => 1 ) )

$input = array(array('id'=>3,'location_id'=>2,'location_name'=>'1st Floor','type'=>1),
array('id'=>6,'location_id'=>2,'location_name'=>'1st Floor','type'=>1),
array('id'=>7,'location_id'=>1,'location_name'=>'Ground Floor','type'=>1)
);
$conct = array();
foreach($input as $k => $_input) {
foreach($_input as $key => $value) {
if(isset($conct[$key])) {
if(check_duplicate($duplicate,$input[$k])) {
$conct[$key] .= ",".$value;
} else {
$new[$key] = $value;
}
}
else
{
$conct[$key] = $value;
if($key=='location_id'||$key=='location_name')
$duplicate[$key] = $value;
}
}
}
function check_duplicate($duplicate=array(),$input=array()) {
foreach($duplicate as $dupe) {
if($dupe===$input['location_id'] || $dupe === $input['location_name'] )
return true;
else
return false;
}
}
echo "<pre>"; print_r($conct);
echo "<pre>"; print_r($new);

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

PHP - Multidimentional array filtering by given value

Array (
[01755677011] => Array (
[0] => Array (
[0] => 1
[id] => 1
[1] => 01755677011
[phone_num] => 01755677011
[2] => NoAnswer
[status] => Answer
)
[1] => Array (
[0] => 2
[id] => 2
[1] => 01755677011
[phone_num] => 01755677011
[2] => NoAnswer
[status] => NoAnswer
)
[2] => Array (
[0] => 3
[id] => 3
[1] => 01755677011
[phone_num] => 01755677011
[2] => Answer
[status] => NoAnswer
)
[3] => Array (
[0] => 4
[id] => 4
[1] => 01755677011
[phone_num] => 01755677011
[2] => Answer
[status] => Answer
)
)
[01755677012] => Array (
[0] => Array (
[0] => 16
[id] => 16
[1] => 01755677012
[phone_num] => 01755677012
[2] =>No Answer
[status] => NoAnswer
)
[1] => Array (
[0] => 18
[id] => 18
[1] => 01755677012
[phone_num] => 01755677012
[2] => Answer
[status] => Answer
)
)
)
This is my current array. I want to filter only Answer status by phone_num.
Outpout Will Like this:
Phone Num No of answer
01755677011 0,23
01755677012 1
Can anyone helo me please ??
I do not understand how you get 0,23 for 01755677011. If you are displaying phone_num and the number of times it has "Answer" status, you can do it this way:
$result = array();
foreach ($num as $key => $row) {
$result[$key] = array();
$count = 0;
foreach($row as $key_value => $row_value) {
if ($row_value['status'] == 'Answer') {
// $key is the key 01755677011 and 01755677012
$result[$key]['id'][$count] = $row_value['id'];
$count++;
}
}
}
if (!empty($result)) {
echo "Phone Num | No of answer<br />";
foreach ($result as $key => $row) {
echo $key . " " . count($row['id']) . "<br />";
}
}
Second version:
1) Based on "Answer" in either [status] or [2].
2) Display array index of the corresponding phone_num.
$result = array();
foreach ($num as $key => $row) {
$result[$key] = array();
$count = 0;
foreach($row as $key_value => $row_value) {
if ($row_value['2'] == 'Answer' || $row_value['status'] == 'Answer') {
// $key is the key 01755677011 and 01755677012
$result[$key][$count]['index'] = $key_value;
$count++;
}
}
}
print_r($result);
if (!empty($result)) {
echo "Phone Num | No of answer<br />";
foreach ($result as $key => $row) {
echo $key . " | ";
if (!empty($row)) {
foreach ($row as $data_key => $data) {
echo $data['index'];
}
} else {
echo "No record";
}
echo "<br />";
}
}

Php array iteration

I have following array :
[1] => Array
(
[entity_id] => 5877
[parent_id] => 5862
[label] => Railbikes
[name] => railbikes
[icon] => books.svg
[level] => 5
[tab_id] => 353
)
[2] => Array
(
[entity_id] => 5756
[parent_id] => 5754
[label] => Tournaments
[name] => tournaments
[icon] => books.svg
[level] => 5
[tab_id] => 354
)
[3] => Array
(
[entity_id] => 5756
[parent_id] => 5754
[label] => Tournaments
[name] => tournaments
[icon] => books.svg
[level] => 5
[tab_id] => 357
)
In this array label => Tournaments repeats twice and this is the case for whole array many labels are repeating twice , thrice and many time .
I want this array to be shown like that there will be a unique label and there is tab_id in each array which is different . This tab_id sholdd be appended to the unique label .
The final array should look like this .
[1] => Array
(
[entity_id] => 5877
[parent_id] => 5862
[label] => Railbikes
[name] => railbikes
[icon] => books.svg
[level] => 5
[tab_id] => 353
)
[2] => Array
(
[entity_id] => 5756
[parent_id] => 5754
[label] => Tournaments
[name] => tournaments
[icon] => books.svg
[level] => 5
[tab_id] => 354 , 357
)
Thanks.
$arr = array(1 => array
(
entity_id => 5877,
parent_id => 5862,
label => Railbikes,
name => railbikes,
icon => books.svg,
level => 5,
tab_id => 353
),
2 => array
(
entity_id => 5756,
parent_id => 5754,
label => Tournaments,
name => tournaments,
icon => books.svg,
level => 5,
tab_id => 354
),
3 => array
(
entity_id => 5756,
parent_id => 5754,
label => Tournaments,
name => tournaments,
icon => books.svg,
level => 5,
tab_id => 357
)
);
print("<pre>");
foreach ($arr AS $key => $value){
/*foreach ($value AS $innerKey => $innerValue){
}*/
if($arr[$key]['label'] == $arr[$key-1]['label'] )
{
$newArr[$key-1]['tab_id'] = $arr[$key]['tab_id'].",". $arr[$key-1]['tab_id'];
}
else{
$newArr[$key]= $arr[$key];
}
}
print_r($newArr);
Try this out
$new_array = array();
$items = array();
foreach( $array as $item )
{
$check = array_search( $item['entity_id'], $items, true );
if ( $check === false )
{
$temp = $item;
$temp['tab_id'] = array( $item['tab_id'] );
$new_array[] = $temp;
$items[] = $temp['entity_id'];
}
else
{
$new_array[$check]['tab_id'][] = $item['tab_id'];
}
}
where $array is your original array the you showed us. You can replace it at the end with $array = $new_array; if you want to keep the same name in the rest of the code.
Also, keep in mind that tab_id is now an array to fit with your requirement.
If you really want to keep it as in your example, you could use
$new_array = array();
$items = array();
foreach( $array as $item )
{
$check = array_search( $item['entity_id'], $items, true );
if ( $check === false )
{
$new_array[] = $item;
$items[] = $item['entity_id'];
}
else
{
$new_array[$check]['tab_id'] .= ', '.$item['tab_id'];
}
}
If the entity_id is always the same then you can 'cheat' a bit:
$new_array = array();
foreach($array as $item)
{
if(!isset($new_array[$item['entity_id']]) $new_array[$item['entity_id']] = $item;
}
$new_array = array_values($new_array);
PS: Always try to prevent double data, doesn't make your script faster ;)

How to loop over associative array using foreach loop construct in following scenairo?

I've an array titled $rebate_by_product:
Array
(
[op] => preview
[id] =>
[form_submitted] => yes
[company_id] => 46
[1] => Array
(
[pack] => 10
[quantity] => 20
[volume] => 30
[units] => 9
[amount] => 40
[rebate_start_date] => 2014-05-01
[rebate_expiry_date] => 2014-05-05
[applicable_states] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[rebate_total_count] => 5000
[products] => Array
(
[1] => 9
[2] => 10
)
)
[2] => Array
(
[pack] => 50
[quantity] => 60
[volume] => 70
[units] => 10
[amount] => 80
[rebate_start_date] => 2014-05-06
[rebate_expiry_date] => 2014-05-10
[applicable_states] => Array
(
[0] => 14
[1] => 15
[2] => 16
)
[rebate_total_count] => 10000
[products] => Array
(
[1] => 11
[2] => 8
)
)
[3] => Array
(
[pack] => 100
[quantity] => 200
[volume] => 300
[units] => 7
[amount] => 400
[rebate_start_date] => 2014-05-21
[rebate_expiry_date] => 2014-05-30
[applicable_states] => Array
(
[0] => 26
[1] => 33
[2] => 42
)
[rebate_total_count] => 9999
[products] => Array
(
[1] => 9
[2] => 8
)
)
[multiselect] => 42
)
You can observe from above array that it has few elements which are not array but it has three such elements which are themselves array and even few of its data elements are also arrays so how to loop over this kind of array using foreach loop?
If you just want to print each one the just use foreach loop. Consider this example:
$product_keys = array(); // edited
// loop them, if its an array, loop inside it again
foreach($rebate_by_product as $index => $element) {
if(is_array($element)) {
foreach($element as $key => $value) {
if(is_array($value)) {
// EDITED
if($key == 'products') {
$product_keys = array_merge($product_keys, $value);
}
$value = implode(',', $value);
echo "$key => $value <br/>";
} else {
echo "$key => $value <br/>";
}
}
} else {
echo "$index => $element <br/>";
}
}
// if product items has duplicates check here (edited)
if(count($product_keys) != count(array_unique($product_keys))) {
echo "<script>alert('This array has duplicate products');</script>";
} else {
echo "<script>alert('Products are ok');</script>";
}
Or if you want, you cant just use iterators on this one:
$recursive = new RecursiveIteratorIterator(new RecursiveArrayIterator($rebate_by_product));
foreach($recursive as $key => $value) {
echo "$key => $value <br/>";
}
I'd propose you're use a recursive approach to bring all the entries of the array on the same level and then print this array:
function loopArray($inputVal,$inputKey = "") {
if(is_array($inputVal)) {
$output = array();
foreach($inputVal as $key => $value) {
$output = array_merge($output,loopArray($value,$key));
}
return $output;
} else {
return array($inputKey => $inputVal);
}
}
// Just for presenting:
$yourArray = array(
"1" => "1",
array(
"2.1" => "2.1",
array(
"2.2.1" => "2.2.1"
)
),
"3" => "3",
array(
"4.1" => "4.1"
)
);
$newArray = loopArray($yourArray);
// > array("1" => 1,"2.1" => "2.1","2.2.1" => "2.2.1","3" => "3","4.1" => "4.1")
foreach($newArray as $key => $value) {
echo $key." => ".$value."<br/>";
}
// > 1 => 1
// > 2.1 => 2.1
// > 2.2.1 => 2.2.1
// > 3 => 3
// > 4.1 => 4.1

PHP - merging 2D array by keys

How can I merge these array together?
Array
(
[0] => Array
(
[type] => Person
[relevance] => 0.700000
[count] => 300
[text] => Chris
)
)
Array
(
[0] => Array
(
[type] => Person
[relevance] => 0.900000
[count] => 400
[text] => Chris
)
[1] => Array
(
[type] => Person
[relevance] => 0.500000
[count] => 200
[text] => Tom
)
)
or array like this:
Array
(
[0] => Array
(
[type] => Person
[relevance] => 0.700000
[count] => 300
[text] => Chris
)
[1] => Array
(
[type] => Person
[relevance] => 0.900000
[count] => 400
[text] => Chris
)
[2] => Array
(
[type] => Person
[relevance] => 0.500000
[count] => 200
[text] => Tom
)
)
The expected result is:
Array
(
[0] => Array
(
[type] => Person
[relevance] => 0.800000
[count] => 700
[text] => Chris
)
[1] => Array
(
[type] => Person
[relevance] => 0.500000
[count] => 200
[text] => Tom
)
)
[relevance] value is an average number
[count] value is an incremental number
The merging of these array should base on [text] value.
How can I do this with php in a fast way?
Thanks for helping.
If this is the array
$array = Array(
Array(
'type' => 'Person',
'relevance' => .7,
'count' => 300,
'text' => 'Chris'
),
Array(
'type' => 'Person',
'relevance' => .9,
'count' => 400,
'text' => 'Chris'
),
Array(
'type' => 'Person',
'relevance' => .5,
'count' => 200,
'text' => 'Tom'
),
);
then:
$tmp = Array();
foreach($array as $obj) {
if(!isset($tmp[$obj['text']])) {
$tmp[$obj['text']] = array_merge(Array('total_count'=>1),$obj);
continue;
}
$tmp[$obj['text']]['count'] += $obj['count'];
$tmp[$obj['text']]['relevance'] += $obj['relevance'];
$tmp[$obj['text']]['total_count']++; // useful for average calculation
}
$result = Array();
foreach($tmp as $key=>$obj) {
$obj['relevance'] = $obj['relevance']/$obj['total_count'];
unset($obj['total_count']); // useless now
$result[] = $obj;
}
print_r($result);
Something like this maybe:
$newArray = array();
foreach ($oldArray as $item) {
if (!array_key_exists($item['text'], $newArray)) {
$newArray[$item['text']] = $item;
$newArray[$item['relevance_values']] = array();
} else {
$newArray[$item['text']]['count'] += $item['count'];
$newArray[$item['relevance_values']][] = $item['relevance'];
}
}
foreach ($newArray as $item) {
$relevance = 0;
foreach ($item['relevance_values'] as $value) {
$relevance += $value;
}
$item['relevance'] = $relevance / count($item['relevance_values']);
}
Try this:
function mergeOnText($array){
$results = array();
foreach($array as $person){
$found = -1;
foreach($results as $i => $res)
if($res['text'] == $person['text']){
$found = $i;
break;
}
if($found > -1){
$results[$found]['relevance'][] = $person['relevance'];
$results[$found]['count'] += $person['count'];
} else {
$results[] = $person;
}
}
foreach($results as $i => $res)
$results[$i]['relevance'] = array_sum($res['relevance']) / count($res['relevance']);
return $results;
}

Categories