Joining Two Arrays Together and Counting Unique Id by using Laravel, PHP - php

I have those two arrays that I added to attachments.
"PartnerAffiliateCodeId" from first array and "Id" from second array is our primary key.
"UserAction" must be counted for every unique "PartnerAffiliateCodeId" so in our case it is 5.
Normally I think this must be done by SQL but unfortunately this is a API method that I am receiving so I have to handle it by PHP.
Any ideas about how I can make such join with PHP using these two arrays?

I'm unclear on exactly what you're trying to get at with UserAction, but you could try something like this:
//$array1 = the first array
//$array2 = the second array
array_push($array_1, array(
"DateTime" => "",
"HttpReferer" => "",
"Id" => count($array1),
"PartnerAffiliateCodeId" => $array2["Id"],
"UserAction" => "Click"
));

It sounds like you want to match the ID key to the PartnerAffiliateCodeId in your returned data set.
Without knowing your setup, or bothinging with total optimization here a workable solution which will give you some direction.
function selectPartnerWhere($id=null; $from=array())
{
$codes = array();
foreach($from as $k => $p)
{
if($id == $p['PartnerAffiliateCodeId'])
{
return $from[$k];
}
}
return array();
}
$theData = //your array above
$thePartner = //your partner above
$partnerData = selectPartnerWhere($thePartner['Id'], $theData);

Related

Find the longest matching string in an array

I have an array of hierarchically arranged identifiers (SNMP sysObjectIDs), that I'd like to match against in order to find the closest match.
For example, if my array contains :
.1.3.6.1.4.1.207 = alliedware
.1.3.6.1.4.1.207.1.14 = alliedwareplus
.1.3.6.1.4.1.207.1.4.126 = allied-radlan
.1.3.6.1.4.1.207.1.4.125 = allied-radlan
And I search for
.1.3.6.1.4.1.207.1.14.69
I would like it to return the alliedwareplus entry.
If I search for
.1.3.6.1.4.1.207.1.4
It should return the alliedware entry.
Basically I just want to return the longest match starting from the beginning of the string.
Thanks in advance!
This worked for me and returns the correct test results based on your description.
function find_match($data,$search) {
$keys = array_keys($data);
usort($keys,function($a,$b){
return strlen($b)-strlen($a);
});
foreach($keys as $key){
if (substr($search,0,strlen($key)) == $key)
return $data[$key];
}
}
$data = array(
'.1.3.6.1.4.1.207' => 'alliedware',
'.1.3.6.1.4.1.207.1.14' => 'alliedwareplus',
'.1.3.6.1.4.1.207.1.4.126' => 'allied-radlan',
'.1.3.6.1.4.1.207.1.4.125' => 'allied-radlan',
);
find_match($data,'.1.3.6.1.4.1.207.1.14.69'); // => 'alliedwareplus'
find_match($data,'.1.3.6.1.4.1.207.1.4'); // => 'alliedware'
Sort the array by the number of components in the object ID, from high to low.
Loop through the array, testing whether the object ID in the array is a prefix of the input object ID.
When you find a match like this, break out of the loop.
All these steps will probably be easiest if you first convert all the object IDs to an array:
$objid_arr = explode('.', $objid);

choosing a specific value from a series of values array php

I have an array which looks like this:
I need to have the array in this format for use later in the script.
//this is only 1 values set there are others that are returned.
Array
(
[DealerName] => Auto Bavaria Midrand MINI
[CustomersCounted] => 16
[Satisfied_Y] => 10
[Satisfied_N] => 6
[InterviewDate] => 2012-01-13
)
I have called the array $customerSatisfactionRatings which I loop through.
foreach($customerSatisfactionRatings as $customerSatisfactionRating) {
$content .= $customerSatisfactionRating';
}
This returns the correct values into the content variable.
What I am interested in is creating a string from the [Satisfied_Y] key.
an example of what I need is $content = '10,5,15,7,8,9,0,3';
I know how to make the string, but not how to extract only the [Satisfied_Y] key.
This makes me sad.
You use a mapping function to pull every Satisfied_Y column out of each $customerSatisfactionRatings item and then you join the results together:
$content = join(',', array_map(function($item) {
return $item['Satisfied_Y'];
}, $customerSatisfactionRatings));
This assumes that each item in $customerSatisfactionRatings is an array as described in your question.
See also: array_map()
I think it will work. Try this,
$satisfyY = array();
foreach($customerSatisfactionRatings as $customerSatisfactionRating) {
$content .= $customerSatisfactionRating;
$satisfyY = $customerSatisfactionRating['Satisfied_Y'];
}
Then implode it to make a string.
$sat_Y = implode(",", $satisfyY);
foreach($customerSatisfactionRatings as $temp)
if (isset($temp['Satisfied_Y']))
{
if (isset($content)) $content.=','.$temp['Satisfied_Y'];
else $content=$temp['Satisfied_Y'];
}

Removing similar elements from a PHP array

I have an array structured like this:
$arrNames = array(
array('first'=>'John', 'last'=>'Smith', 'id'=>'1'),
array('first'=>'John', 'last'=>'Smith', 'id'=>'2'),
array('first'=>'John', 'last'=>'Smith', 'id'=>'3')
)
I need to remove the similar elements where the fist and last name are the same. Normally, I would use array_unique but the elements aren't exactly unique since each one has a unique id. I do not care which id is retained. I just need the array to look like this:
$arrNames = array(
array('first'=>'John', 'last'=>'Smith', 'id'=>'1') // can be any id from the original array
)
Is there a quick way to accomplish this? My first thought is to use something like a bubble sort but I'm wondering if there is a better (faster) way. The resulting array is being added to a drop-down list box and the duplicate entries is confusing some users. I'm using the ID to pull the record back from the DB after it is selected. Therefore, it must be included in the array.
<?php
$arrNames = array(
array('first'=>'John', 'last'=>'Smith', id=>'1'),
array('first'=>'John', 'last'=>'Smith', id=>'2'),
array('first'=>'John', 'last'=>'Smith', id=>'3')
);
$arrFound = array();
foreach ($arrNames as $intKey => $arrPerson) {
$arrPersonNoId = array(
'first' => $arrPerson['first'],
'last' => $arrPerson['last']
);
if (in_array($arrPersonNoId, $arrFound)) {
unset($arrNames[$intKey]);
} else {
$arrFound[] = $arrPersonNoId;
}
}
unset($arrFound, $intKey, $arrPerson, $arrPersonNoId);
print_r($arrNames);
This definitely works, whether it is the best way is up for debate...
Codepad
There is no fast and easy way that I know of, but here is a relatively simple way of doing it assuming that the ids for "similar elements" don't matter (i.e. you just need an ID period).
$final = array();
foreach ($array as $values) {
$final[$values['first'] . $values['last']] = $values;
}
$array = array_values($final);
The last step is not strictly necessary .. only if you want to remove the derived keys.

Retrieving array/sub-array name for use in php

I have a multi-dimensional array of databases, which was generated from my server:
// place db tables into array
$da_db = array(
'test' => array(
// test.users
'users' => array('fname','lname','info'),
// test.webref_rss_details
'webref_rss_details' => array('id','title','link','description','language','image_title','image_link','item_desc','image_width','image_height','image_url','man_Edit','webmaster','copyright','pubDate','lastBuild','category','generator','docs','cloud','ttl','rating','textInput','skipHours','skipDays'),
// test.webref_rss_items
'webref_rss_items' => array('id','title','description','link','guid','pubDate','author','category','comments','enclosure','source','chan_id')
),
'db_danaldo' => array(
//code here
),
'frontacc' => array(
//code here
)
[array][db][table][field]
As you can see, the database currently populated refers to an RSS project I am working on - one table for Channels, another for Items in that channel, at the moment that is another issue ('Users' table for now is not important)..
what I want to do is to return the array/sub-array names and convert each into variables for use as part of a string in an SQL Query, also need an alias for the tables I need to connect with:
(e.g. SELECT * FROM 'webref_rss_items' WHERE 'chan_id' = 'test.webref_rss_details.id')
where 'webref_rss_items' is a variable, 'chan_id' is a variable and 'test.webref_rss_details.id' are 3 variables in a concatenated string, although I've heard the concatenation in an SQL Query is not good practice, security-wise.. the strange thing is of all of those values, all I can retreive is the deepest level, 'id':
echo "{$da_db['test']['webref_rss_details'][0]}"
but get 'Array' returned or the last value of an array when I try to access the names!!
The reason for this is that the PHP file with the query will be within the 'public' part of the server and would like to have use variables with have no connotation to the original name(s), also it seems more convenient as the variables can be interchangable and I won't be using the same path all the time.
EDIT: My idea is to get key names from ['db'] to ['field']. The closest I have reached is to iterate keys and array_fill in a foreach loop, use range() inside another foreach, array_combine both then var_dump combined array like so:
foreach($da_db['test'] as $key1 => $val) { //put key-names into array1 to use as values
$a = array();
$a = array_fill(0, 1, $key1);
print($key1.'<br />');
}
foreach (range(0, 2) as $number) { //array for numbers to use as keys
$b = array();
$b = array_fill(0, 1, $number);
echo $number.'<br />';
}
$c = array_combine($b, $a); //combine both for new array
print_r($c.'<br />');
I could the use array_slice to get the name I want! (long winded?)
The problem is that the result of this only shows the last key => value; depending on command(print_r, print, echo), it shows:
[2] => webref_rss_items
OR
Array.
I hope that is enough info for now.
I've seen similar questions on here, but normally apply to one value, or one level of an array, but if you have seen this question before please advise and point me in right direction.
Your two top level arrays (db name and table name) are "named-key" arrays. The field level array (value of table name array) is an "integer key" array. PHP automatically adds numerical indexes for arrays that are defined with values only. For "named-key" arrays, you can only access their values by using the key name you defined.
For example:
$array1 = array('zero', 'one', 'two');
echo $array1[2]; // two
$array2 = array('zero' => 'this is zero', 'one' => 'this is one');
echo $array2['zero']; // this is zero
echo $array2[0]; // undefined
PHP provides a function called array_keys() that will return you an integer index array with all the key names. So you access your table array using an integer value, you can do this.
$da_db_test_keys = array_keys($da_db['test']);
echo $da_db_test_keys[1];
Maybe this will help you a little bit. I wasn't 100% on how you planned on accessing the values in your arrays, so if you have any more questions please try to clarify that part.

Change the array KEY to a value from sub array

This is the set of result from my database
print_r($plan);
Array
(
[0] => Array
(
[id] => 2
[subscr_unit] => D
[subscr_period] =>
[subscr_fee] =>
)
[1] => Array
(
[id] => 3
[subscr_unit] => M,Y
[subscr_period] => 1,1
[subscr_fee] => 90,1000
)
[2] => Array
(
[id] => 32
[subscr_unit] => M,Y
[subscr_period] => 1,1
[subscr_fee] => 150,1500
)
)
How can I change the $plan[0] to $plan[value_of_id]
Thank You.
This won't do it in-place, but:
$new_plan = array();
foreach ($plan as $item)
{
$new_plan[$item['id']] = $item;
}
This may be a bit late but I've been looking for a solution to the same problem. But since all of the other answers involve loops and are too complicated imho, I've been trying some stuff myself.
The outcome
$items = array_combine(array_column($items, 'id'), $items);
It's as simple as that.
You could also use array_reduce which is generally used for, well, reducing an array. That said it can be used to achieve an array format like you want by simple returning the same items as in the input array but with the required keys.
// Note: Uses anonymous function syntax only available as of PHP 5.3.0
// Could use create_function() or callback to a named function
$plan = array_reduce($plan, function($reduced, $current) {
$reduced[$current['id']] = $current;
return $reduced;
});
Note however, if the paragraph above did not make it clear, this approach is overkill for your individual requirements as outlined in the question. It might prove useful however to readers looking to do a little more with the array than simply changing the keys.
Seeing the code you used to assemble $plan would be helpful, but I'm going assume it was something like this
while ($line = $RES->fetch_assoc()) {
$plan[] = $line;
}
You can simply assign an explicit value while pulling the data from your database, like this:
while ($line = $RES->fetch_assoc()) {
$plan[$line['id']] = $line;
}
This is assuming $RES is the result set from your database query.
In my opinion, there is no simpler or more expressive technique than array_column() with a null second parameter. The null parameter informs the function to retain all elements in each subarray, the new 1st level keys are derived from the column nominated in the third parameter of array_column().
Code: (Demo)
$plan = array_column($plan, null, 'id');
Note: this technique is also commonly used to ensure that all subarrays contain a unique value within the parent array. This occurs because arrays may not contain duplicate keys on the same level. Consequently, if a duplicate value occurs while using array_column(), then previous subarrays will be overwritten by each subsequent occurrence of the same value to be used as the new key.
Demonstration of "data loss" due to new key collision.
$plans = array();
foreach($plan as $item)
{
$plans[$item['id']] = $item;
}
$plans contains the associative array.
This is just a simple solution.
$newplan = array();
foreach($plan as $value) {
$id = $value["id"];
unset($value["id"]);
$newplan[$id] = $value;
}

Categories