PHP Array custom fusion of values - php

Good morning!
I'm using a SQL query to get category IDs from posts. Several post can have the same ID if they are from the same category. This is my array:
Array (
[0] => stdClass Object ( [catid] => 48 )
[1] => stdClass Object ( [catid] => 77 )
[2] => stdClass Object ( [catid] => 57 )
[3] => stdClass Object ( [catid] => 57 )
[4] => stdClass Object ( [catid] => 38 ))
Now I need to get the sum of all different catid's (in this case 4). I could achieve this by using "distinct" or a "group by" in my SQL, anyway I didnt because they mess up my results.
The problem is, that some catids should be replaced. For example is catid 48 'HDDs' and 77 is 'Storage' so 48 should be a part of 77 (So the sum is now 3). I already got an array of the catids that should be merged:
$catMergeArray = array(
38=>74,36=>46,34=>72,37=>73,40=>76,39=>75,103=>85,102=>81,53=>82,51=>80,50=>79,
55=>90,56=>91,57=>92,58=>93,55=>90,104=>68,106=>69,65=>70,66=>86,108=>95,48=>77,
172=>171,105=>170,111=>169);
by using
foreach ($result as $cats) {
$newarray[] = $cats->catid;
}
I changed my Array to
$newarray = Array ([0] => 48 [1] => 77 [2] => 57 [3] => 57 [4] => 38)
Then (like mentioned in $catMergeArray where it says 48=>77) remove the [0] => 48 value so the result should be $catids = Array ([0] => 77 [1] => 57 [2] => 38) so I can count the elements and have 3 as result to work with.

ummm have you tried using array_unique? http://php.net/manual/en/function.array-unique.php
or you can also group them into a unique array index like this:
$summary = array();
foreach( $catids as $catid => $cat){
$summary[$catid][] = $cat;
}

It'd probably be better to do it in php. Here's a rough idea and some pseudocode.
probably not very efficent nor elegent, but it should work.
$list_of_id = mysqli_fetch_array(query("distinct catId"));
for($i=0;$i<count($list_of_id);$i++){
$parent_cat_id = $catMergeArray[$list_od_id[$i]];
if ($parent_cat_id > 0){
for($j=0;$j<count($list_of_id);$j++){
if($list_of_id[$j]==$parent_cat_id){
unset($list_of_id[$i]);
break;
}
}
}
}
echo count($list_of_id);
EDIT: since OP doesn't seems to understand pseudocode...I'll make a php version... Surely it's clear enough?

Thanks for all the help. I now solved my problem with this:
foreach ($result as $value) {
$intArray[] = $value->catid;
}
$uniqueArray = array_unique($intArray);
$cUniqueArray = count($uniqueArray);
$cma = array(48=>77);
$lenght = $cUniqueArray-1;
for($i = 0; $i <= $lenght; $i++){
$key = array_search($uniqueArray[$i],$cma);
if(is_int($key)){
$uniqueArray[$i] = $key;
}
}

Related

PHP, array manipulation to get keys with all same name

I have this array posting to my controller:
Array
(
[id] => Array
(
[0] => 95
[1] => 69
)
)
I want:
Array(
[id] => 95
[id] => 69
)
As I am using CodeIgniter's $this->db->delete() function and it takes the array key value as the column for the WHERE clause. I have this code at the moment:
foreach($ids as $k => $v){
$formatIds['id'] = $v;
}
Which just gives me one of the rows and not the rest.
I then tried:
foreach($ids as $k => $v){
$formatIds['id'][] = $v;
}
But this gives me a MultiDimensional array...
The answer to your question is "not possible": array keys must always be unique.
The answer to what you're trying to do is to use where_in():
$names = array(95,69);
$this->db->where_in('id', $names);
$this->db->delete('mytable');

How to remove duplicate entries from associative array in php

My array is
Array
(
[0] => Array
(
[id] => 20
[new_id] => 958
[affiliate_id] => 33
)
[1] => Array
(
[id] => 21
[new_id] => 959
[affiliate_id] => 45
)
[2] => Array
(
[id] => 22
[new_id] => 960
[affiliate_id] => 23
)
[3] => Array
(
[id] => 23
[new_id] => 961
[affiliate_id] => 33
)
)
and i want array
Array
(
[0] => Array
(
[id] => 20
[new_id] => 958
[affiliate_id] => 33
)
[1] => Array
(
[id] => 21
[new_id] => 959
[affiliate_id] => 45
)
[2] => Array
(
[id] => 22
[new_id] => 960
[affiliate_id] => 23
)
)
I want to remove duplicates value of affiliate_id . According to first array i am getting affiliate_id's value is 33 for two time. But i want it for one time. So in my second array (which will be my answer) i remove it.
Try something like this, not so pretty as array_ one liners, but still:
$existing_aff_ids = array();
$unique = array();
foreach ($affiliate as $aff) {
if (!isset($existing_aff_ids[$aff['affiliate_id']])) {
$unique[] = $aff;
$existing_aff_ids[$aff['affiliate_id']] = 1;
}
}
Given $affiliates as in your answer, looping over the array and checking for affiliate_id would do the trick
$unique_affiliates = array();
foreach($affiliates as $affiliate) {
$affiliate_key = $affiliate['key'];
/* Variant 1 */
$unique_affiliates[$affiliate_key] = $affiliate;
/* Variant 2 */
if(!isset($unique_affiliates[$affiliate_key])) {
$unique_affiliates[$affiliate_key] = $affiliate;
}
}
All entries in $unique_affiliates will have unique affiliate_keys. Variant 1 will contain the last occurrence of each afffiliate_key (as in your example), whereas variant 2 will add the first occurrence of any affiliate_key and just ignore all subsequent ones.
These are not duplicate values :
1. $input = array_map("unserialize",
array_unique(array_map("serialize", $data))
2. array_values(array_unique($data))
Both this case fails because of the unique id values are there it requires all values to be same to consider it as duplicate.
Solution:Will making the array check the value of the corresponding field.
foreach($data as $key=>$val)
{
if (is_array($val))
{
$val2 = arrayUnique($val);
}
else
{
$val2 = $val;
$newArray=array_unique($data);
$newArray=deleteEmpty($newArray);
break;
}
if (!empty($val2))
{
$newArray[$key] = $val2;
}
}
print_r($newArray);

get nth array row number php

Suppose you have the following array values assigned to a variable,
$erz = Array (
[0] => stdClass Object ( [id] => 43 [gt] => 112.5 )
[1] => stdClass Object ( [id] => 47 [gt] => 46 )
[2] => stdClass Object ( [id] => 48 [gt] => 23.75 )
[3] => stdClass Object ( [id] => 49 [gt] => 12.5 )
)
I need to be able to get the array index number given the id. So for instance I want to get 2 given id 48, or get 3 given id 49, etc. Is there a php command able to do this?
I dont think there is but its easy to set up your own function..
function findArrayIndex($arr, $searchId) {
$arrLen = count($arr);
for($i=0; $i < $arrLen; $i++) {
if($arr[$i][id] == $searchId) return $i;
}
return -1;
}
No, there is no such funcion. There is an array_search() actually, but you can't use it with objects. For example, here has been asked a simmilar question: PHP - find entry by object property from a array of objects
So you have to make your own loop:
$result = null;
$givenID = 43;
foreach ($erz as $key => $element)
{
if ($element->id == $givenID)
$result = $key;
}

Trying to parse through SQL data to make an easier-to-handle associative array

I'm using Wordpress for this, but it is not a Wordpress-centric issue, so I am asking here.
You can see a snippet of my code here: http://pastebin.com/Cbc8wKvB
<?php
function getFormIds()
{
global $wpdb;
$sql = "
SELECT a.id
FROM wp_rg_lead a
WHERE a.form_id = 10 AND a.payment_status = 'Approved'
";
$query = $wpdb->get_results($sql);
if($query)
return $query;
return false;
}
function getFormInfo($form_id)
{
global $wpdb;
$sql = "
SELECT *
FROM wp_rg_lead_detail
WHERE lead_id = $form_id
";
$query = $wpdb->get_results($sql);
if($query)
return $query;
return false;
}
$credit_card_form_ids = getFormIds();
if ( $credit_card_form_ids ) {
$entries = array();
foreach( $credit_card_form_ids as $entry) {
$single_entry = getFormInfo($entry->id);
if ( $single_entry ) {
$entry_array = array();
$full_array = array();
foreach( $single_entry as $entry ) {
$curr_array = array( $entry->field_number => strip_tags($entry->value));
$entry_array[$entry->field_number] = strip_tags($entry->value);
array_push($full_array, $entry_array);
}
}
}
#var_dump('full_array', $full_array);
}
Basically I'm running a DB query to grab all entry ID's that match a certain criterion. This returns an array of objects of single values. I then pass this array through a foreach() and try to extract/combine data to make it easier to work with.
Here is a print_r() of a $single_entry from the code above: http://pastebin.com/RZmfD2EU
single entry:
Array
(
[0] => stdClass Object
(
[id] => 1983
[lead_id] => 86
[form_id] => 10
[field_number] => 34
[value] => 695
)
[1] => stdClass Object
(
[id] => 1982
[lead_id] => 86
[form_id] => 10
[field_number] => 39
[value] => 0
)
[2] => stdClass Object
(
[id] => 1981
[lead_id] => 86
[form_id] => 10
[field_number] => 40.1
[value] => Yes
)
... etc etc.
With the code I provided, the final array seems to collapse somehow -- meaning I lose entries somewhere along the way.
Ideally I'd love the data to associate id's to their key => value pairs. Namely:
[id] => [lead_id]
[field_number#] => [field_number_value]
For a actual representation of the first few lines of data provided:
Array (
[0] =>
(
[id] => 86
[34] => 695
[39] => 0
[40.1] => Yes
...etc
)
)
Is there a better way to loop through and associate data than what I'm doing? I'm relatively new/bad at PHP and MySQL and would love some guidance.
I'm not sure if I'm understanding it right but if you want to assign values to specified keys…
if ( $single_entry ) {
$entry_array = array();
$full_array = array();
foreach( $single_entry as $entry ) {
$curr_array = array( $entry->field_number => strip_tags($entry->value));
$entry_array[$entry->field_number] = strip_tags($entry->value);
$lead_id = $entry['lead_id'];
$full_array[$lead_id] = $entry_array;
}
}

Loop through array and remove duplicates

I have the following array for tire sizes:
Array
(
[0] => 155
[1] => 70
[2] => 13
)
Array
(
[0] => 155
[1] => 80
[2] => 13
)
Array
(
[0] => 165
[1] => 65
[2] => 14
)
Array
(
[0] => 175
[1] => 65
[2] => 14
)
Array
(
[0] => 175
[1] => 70
[2] => 13
)
Array
(
[0] => 175
[1] => 70
[2] => 14
)
and so on. Now I am creating a drop down so people can select the tire size they are searching for. so here is my PHP code:
include 'database.php';
$result = $mysqli->query('SELECT DISTINCT SKU_SIZE FROM SKU_DATA WHERE SKU_BRANDNAME = "'.$brand.'" ORDER BY SKU_SIZE');
while( $row = $result->fetch_assoc()){
$sku_size = $row['SKU_SIZE'];
$chars = preg_split('/[^\d]/', $sku_size, -1, PREG_SPLIT_NO_EMPTY);
echo "<option>".$chars[0]."</option>";
}
Now that code is just showing the first number in each array, for the very first drop down they select.
Right now it is showing 155, 155, 165, 175, 175 - and what I want it to do is just show the unique values so it would just show 155, 165, 175.
Update: Thanks! I got that part working. One quick question.. the order is not quite right, not sure what I am doing wrong. Here is a preview:
Create an array and check to see if each value is in the array before outputting it. If it is not in the array, add it in before outputting.
include 'database.php';
$result = $mysqli->query(
'SELECT DISTINCT SKU_SIZE
FROM SKU_DATA WHERE SKU_BRANDNAME = "'.$brand.'"
ORDER BY SKU_SIZE'
);
$seen = array();
while( $row = $result->fetch_assoc()){
$sku_size = $row['SKU_SIZE'];
$chars = preg_split('/[^\d]/', $sku_size, -1, PREG_SPLIT_NO_EMPTY);
if(in_array($chars[0], $seen))
continue;
$seen[] = $chars[0];
echo "<option>".$chars[0]."</option>";
}
You can remove any duplicate unique items from an array using the array_unique() function.
EG:
$arrays = array(1,2,3) + array(1,2,3);
print_r(array_unique($arrays));
// Will print just: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 )
use this:
while( $row = $result->fetch_assoc()){
$sku_size = $row['SKU_SIZE'];
$chars = preg_split('/[^\d]/', $sku_size, -1, PREG_SPLIT_NO_EMPTY);
$sizes[$chars[0]] = true;
}
ksort($sizes, SORT_NUMERIC);
foreach ($sizes as $size => $tmp){
echo "<option value=\"$size\">$size</option>";
}
Use a temporary array to store the numbers that have been echoed then.
Make a new array with just the first value
$diameter = array();
foreach ($tires as $tire) {
$diameter[] = $tire[0];
}
Then, use array_unique() to remove the duplicates, or only add them to $diameter if they are not already in there.
Then use that $diameter array to create the dropdown.
This has the advantage that you can also sort the $diameter array.

Categories