Delete double entries from array - php

I have the following array in php:
[0] => Array(
(
[post_id] => 492,
[user_id] => 1
)
[1] => Array(
(
[post_id] => 501,
[user_id] => 1
)
[2] => Array(
(
[post_id] => 568,
[user_id] => 13
)
[3] => Array(
(
[post_id] => 897,
[user_id] => 13
)
What I want to do, is to delete the ones where the user_id already exists. So the result should look like this:
[0] => Array(
(
[post_id] => 492,
[user_id] => 1
)
[1] => Array(
(
[post_id] => 568,
[user_id] => 13
)
I need an array, in which every user_id only exists one time.
array_unique() doesn't work for this example. Any ideas?
Thanks!

You can loop through and find unique values as you go:
$exists = array();
foreach($items as $key => $item) {
if(!in_array($item['user_id'], $exists)) {
$exists[] = $item['user_id'];
} else {
unset($items[$key]);
}
}
This will unset any arrays that already exist in the $exists array.

Here is the easy function to solve the issue.
$array = Array();
$array[] = Array('post_id'=>492 , 'user_id' => '1');
$array[] = Array('post_id'=>501 , 'user_id' => '1');
$array[] = Array('post_id'=>568 , 'user_id' => '13');
$array[] = Array('post_id'=>897 , 'user_id' => '13');
print_r($array);
print_r(make_unique_by_key($array,'user_id'));
function make_unique_by_key($m_arr , $key) {
$tmp_arr = array();
foreach ($m_arr as &$item) {
if (!isset($tmp_arr[$item[$key]])) {
$tmp_arr[$item[$key]] =& $item;
}
}
$ret_arr = array_values($tmp_arr);
return $ret_arr;
}

Related

Compare values using strpos - PHP

I am trying to return the user_id if value matches with any comma separated value, I am using strpos but I don't why is it not working with 3rd case:
To Compare: (This value is stored in $myArray variable)
Array
(
[0] => cloud
[1] => ai
[2] => test
)
Compare with: (This value is stored in $array_meta_values variable)
Array
(
[0] => Array
(
[tags] => cloud,ai
[user_id] => 1
)
[1] => Array
(
[tags] => cloud,ai,test
[user_id] => 108
)
[2] => Array
(
[tags] => storage,backup,ai
[user_id] => 101
)
)
function searchForId($meta_value, $array)
{
foreach ($array as $key => $val) {
if (strpos($val['tags'], $meta_value)) {
return $val['user_id'];
}
}
}
foreach ($myArray as $usertags) {
$userids[] = searchForId($usertags, $array_meta_values);
}
print_r($userids);
Getting this Output:
Array
(
[1] => 1
[2] => 108
)
It was supposed to add 101 as third element in output array but don't know why it is not working.
Any help appreciated.
Hi so I tried to replicate you question,
$existing = ['cloud', 'ai', 'test'];
$checker = [
array(
"tags" => "cloud,ai",
"user_id" => 1
),
array(
"tags" => "cloud,ai,test",
"user_id" => 108
),
array(
"tags" => "storage,backup,ai",
"user_id" => 101
)
];
function searchForId($meta_value, $array)
{
$ret_array = [];
foreach ($array as $val) {
$et = explode(",", $val['tags']);
if (in_array($meta_value, $et)) {
$ret_array[] = $val['user_id'];
}
}
return $ret_array;
}
foreach ($existing as $usertags) {
$userids[$usertags][] = searchForId($usertags, $checker);
}
echo "<pre>";
print_r($userids);
Is this what you looking for?
Your question is quite unclear, but I'll try with this one:
<?php
$myArray = array('cloud', 'ai', 'test');
$array_meta_values = array(
array(
'tags' => 'cloud,ai',
'user_id' => 1,
),
array(
'tags' => 'cloud,ai,test',
'user_id' => 108,
),
array(
'tags' => 'storage,backup,ai',
'user_id' => 101,
),
);
$userids = [];
foreach ($myArray as $value) {
foreach ($array_meta_values as $array) {
$arrayValues = explode(',', $array['tags']);
if (in_array($value, $arrayValues)) {
$userids[$value][] = $array['user_id'];
}
}
}
echo '<pre>';
print_r($userids);
Output:
Array
(
[cloud] => Array
(
[0] => 1
[1] => 108
)
[ai] => Array
(
[0] => 1
[1] => 108
[2] => 101
)
[test] => Array
(
[0] => 108
)
)

How to prepare a new array out of two arrays inside foreach loop?

I am trying to compare the keys of an array with values of another array. In case of greater values of the current key, I would like to push the value into a new array. Then I want to insert all the collected values for that specific key into a DB table.
These are my input arrays:
$productlist = [result] => Array
(
[0] => Array
(
[configoption1] => 2M
[id] => 96
)
[1] => Array
(
[configoption1] => 5M
[id] => 97
)
[2] => Array
(
[configoption1] => 15M
[id] => 98
)
[3] => Array
(
[configoption1] => 30M
[id] => 99
)
)
$myplans = Array
(
[2M] => Array
(
[price] => 10
)
[5M] => Array
(
[price] => 10
)
[15M] => Array
(
[price] => 10
)
[30M] => Array
(
[price] => 10
)
)
The following is my sample code:
$upgradelist = array()
foreach ($myplans as $plan => $data) {
foreach($productlist['result'] as $key=>$value){
if($plan == 'ENTERPRISE'){
//no higher plans than Enterprise
}else{
$plan1 = (int)substr_replace($plan, "", -1);
$value['configoption1'] = (int)substr_replace($value['configoption1'], "", -1);
#echo " configconfig=> ".$value['configoption1'];
if($plan > $value['configoption1']){
$upgrade_product_ids[$plan][] = $value['id'];
}
}
}
//insert upgrade products list
if(!empty($upgradelist)){
foreach($upgradelist as $key => $upgrade_product_id){
#$insert_stmt_upgradeproduct = <insert statement> for each $plan
}
}
}
expected output each time I come out from the foreach loop: > foreach($productlist['result']
$upgradelist = Array
(
[2] => Array
(
[0] => 97 //5M
[1] => 98 //15M
[2] => 99 //30M
)
)
$upgradelist = Array
(
[5] => Array
(
[0] => 98
[1] => 99
)
)
$upgradelist = Array
(
[15] => Array
(
[0] => 99
)
)
$upgradelist = Array
(
[30] => Array
(
)
)
You can solve like below:
foreach($myplans as $key => $plan) {
$data_to_be_inserted = [];
foreach($productlist['result'] as $product) {
if ($key > $product['configoption1']) {
$data_to_be_inserted [] = $product['id'];
}
}
if (count($data_to_be_inserted)) {
//insert into database(expected value will be available here)
}
}
YOu can do like this
<?php
$myArray = [];
$myArray['result'] = array(
array("configoption1" => "2m", "id" => 96),
array("configoption1" => "5m", "id" => 97),
array("configoption1" => "15m", "id" => 98),
array("configoption1" => "30m", "id" => 99)
);
//print_r($myArray);
$myArray2 =[
"2m" => ["price" => 10],
"5m" => ["price" => 10],
"15m" => ["price" => 10],
"30m" => ["price" => 10]
];
$resultArray = [];
foreach($myArray2 as $key => $values) {
$keyNum = (int)$key;
$newTempArray[$keyNum] = [];
foreach($myArray['result'] as $newresult) {
$configoption1Num = (int)$newresult['configoption1'];
if($configoption1Num > $keyNum) {
array_push($newTempArray[$keyNum], $newresult['id']);
}
}
print_r($newTempArray[$keyNum]);
echo "<br>";
}
http://sandbox.onlinephpfunctions.com/code/008c839fb4fad4ed2aceae7c4ed1220579e8e318

Change key on array_chunk php

I have array based POST like this :
Array
(
[condition] => Array
(
[0] => 1
)
[container] =>
[cleaning] => Y
[owner] => Eagletainer
[last_cargo] => 1
[vessel] =>
[insulation] => 1
[tare] =>
[gross] =>
[capacity] =>
[unit_type] => IMO 1
[date_of_manu] =>
[name_manu] =>
[last25] =>
[cert25] =>
[last5] =>
[cert5] =>
[list2_item_0] => 1
[list2_kondisi_0] => 9
[list3_item_0] => 15
[list3_kondisi_0] => 3
[comments] =>
)
My case is, I want to chunk a lot of those element array into another array for insert_batch in my database.
This is the php code to chunk those array:
public function get_partition($array, $p, $c) {
$partition = array_slice($array, $p);
array_pop($partition);
return $chunk = array_chunk($partition, $c);
}
Now, use it,
$detail = $this->get_partition($this->input->post(), 17, 2);
The result is :
Array
(
[0] => Array
(
[0] => 1
[1] => 9
)
[1] => Array
(
[0] => 15
[1] => 3
)
)
My question in, how to change the key [0] and [1] into another key like [ID] and [CODE_DAMAGE]
I want them looked like this :
Array
(
[0] => Array
(
[ID] => 1
[CODE_DAMAGE] => 9
)
[1] => Array
(
[ID] => 15
[CODE_DAMAGE] => 3
)
)
Re-loop the array and achieve your desired result like this:
$detail = $this->get_partition($this->input->post(), 17, 2);
$new_array = array();
$count = 0;
foreach($detail as $row){
$new_array[$count]['ID'] = $row[0];
$new_array[$count++]['CODE_DAMAGE'] = $row[1];
}
If the indexes were already correct you could pass the optional third parameter: http://php.net/array_chunk
<?php
$array = array(0 => array(0 => 123, 1 => 1234), 1 => array(0 => 123, 1 => 1234));
$updatedArray = array();
foreach ($array as $k => $v) {
$updatedArray[$k]['ID'] = $v[0];
$updatedArray[$k]['CODE_DAMAGE'] = $v[1];
}
?>
Try this, I hope this helps.
Try this:
foreach($detail as $key => $value){
if($key == 0){
$detail['ID'] = $value;
unset($detail[$key]);
}
if($key == 1){
$detail['CODE_DAMAGE'] = $value;
unset($detail[$key]);
}
}
Just an example add your array to this code..it will work fine
$main = Array(Array(1,9),Array(15,3));
$b = array('ID', 'CODE_DAMAGE');
$new_array = array();
foreach($main as $subarray)
{
$new_array[] = array_combine($b, $subarray);
}
echo'<pre>';print_r($new_array);

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 ;)

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