Remove from array if id exists in database? - php

I am pulling data from an api and as such i have a loop that stores some ids into an array.
What i need to do is select all ids from my database and then remove any ids that have been found in the database from the initial array. so i can continue to query the api for ids that i do not have currently.
To make more sense please look below:
$matches = $database->get_results('SELECT match_id FROM `matches` WHERE `order_id`='.$order_id);
if ($matchlist->totalGames !== 0) {
foreach ($matchlist as $key) {
$gameIds[] = $key->matchId;
}
}
I need to remove the ids from $gameIds if they already are stored in the $matches.
Any ideas?
Thanks
I have tried:
$matches = $database->get_results('SELECT `match_id` FROM `matches` WHERE `order_id`='.$order_id);
if ($matchlist->totalGames !== 0) {
foreach ($matchlist as $key) {
$gameIds[] = $key->matchId;
}
$arr_matches = object2array($matches);
$new_array = array_diff($arr_matches, $gameIds);
var_dump($new_array);
}
error:
Catchable fatal error: Object of class stdClass could not be converted to string

Step 1: Change object to array
function object2array($object)
{
if (is_object($object)):
foreach ($object as $key => $value):
$array[$key] = $value;
endforeach;
else:
$array = $object;
endif;
return $array;
}
Step 2:
$arr_matches = object2array($matches)
$new_array = array_diff($arr_matches , $gameIds);
// Will remove all elements contained in $gameIds from $arr_matches array.

Related

“How can to fix the problem ‘ number_format error

I would like to shorten the result. I have used nummber_format but always an error appears.Can someone help me.
$arr = array();
foreach ($order->orderPositions as $tax) {
$arr[] = $tax->tax;
}
$unique_data = array_unique($arr);
foreach ($unique_data as $val) {
$totalTaxes[$val] = $order->orderPositions->where('tax',
$val)->sum('TotalPriceWithTax');
}
/*help is needed here*/ number_format((float)$unique_data,2);
Loop the array and save them as the new format either in a new array or the same
$unique_data = array_unique($arr);
foreach ($unique_data as &$val) { //notice the & if you want to change the data points in the unique array
$totalTaxes[$val] = $order->orderPositions->where('tax', $val)->sum('TotalPriceWithTax');
$val = number_format($val,2); // replaces the data in unique array
$new[] = number_format($val,2); // add to new array if you need unique array
}

Adding data to existing array after using array data

I have an array of data that is being created from a MySQL query which I am then using to create more data which I then need back in the array (or a new one) but I haven't been able to get this working at all.
Here is the code I have been trying to use:
$vars['items'] = $this->_query('SELECT customers.*, sites.site_name as `default_location`
FROM `customers`
JOIN `sites` ON customers.site_id=sites.id');
$a=array();
foreach($vars['items'] as $customer)
{
if($customer['record_to_use'] == '2')
{
$results = dns_get_record($customer['cust_mx'], DNS_MX);
$mx = min(array_column($results, "pri"));
$highest = array_filter(
$results,
function($item) use($mx) {return $item["pri"] === $mx;}
);
foreach ($highest as $mx)
{
$results = dns_get_record($mx["target"], DNS_A);
foreach ($results as $a)
{
$vars['items']['ip'] .= $a['ip'];
}
}
}
}
So I need the IP that gets created from each item in the array to get added into that array as $vars['items']['ip']
Thanks in advance!
foreach ($results as $a => $value)
{
$vars['items'][$a]['ip'] = $value['ip'];
}
That's what I needed :)
$vars['items']['ip'] .= $a['ip'];
.= is concatenation if that was a typo in your code.
Try $vars['items']['ip'] = $a['ip'];

How to parse array from MySQL column in PHP

I have column extra_fields in table.
In column i have array, and I need to parse it
[{"id":"1","value":"fdsds"},{"id":"2","value":"\/images\/powered_by.png"},{"id":"3","value":"fdsfdsfdsfds"},{"id":"4","value":"<p>fdsfdsfdsfds<\/p>"}]
Try to do it with this code,
$extrafields = array();
foreach($this->item->extra_fields as $item)
{
$extrafields[$item->id] = $item->value;
}
but return empty string or...I don't know what
it is unclear as to what you want to achieve but here you go:
$test = json_decode('[{"id":"1","value":"fdsds"},{"id":"2","value":"\/images\/powered_by.png"},{"id":"3","value":"fdsfdsfdsfds"},{"id":"4","value":"<p>fdsfdsfdsfds<\/p>"}]');
$extrafields = array();
foreach ($test as $key => $item) {
$extrafields[$item->id] = $item->value;
}

Compare and replace values in array

I need compare 2 arrays , the first array have one order and can´t change , in the other array i have different values , the first array must compare his id with the id of the other array , and if the id it´s the same , take the value and replace for show all in the same order
For Example :
$array_1=array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2=array("4a-walking","2a-cats");
The Result in this case i want get it´s this :
"1a-dogs","2a-cats","3a-birds","4a-walking"
If the id in this case 4a it´s the same , that entry must be modificate and put the value of other array and stay all in the same order
I do this but no get work me :
for($fte=0;$fte<count($array_1);$fte++)
{
$exp_id_tmp=explode("-",$array_1[$fte]);
$cr_temp[]="".$exp_id_tmp[0]."";
}
for($ftt=0;$ftt<count($array_2);$ftt++)
{
$exp_id_targ=explode("-",$array_2[$ftt]);
$cr_target[]="".$exp_id_targ[0]."";
}
/// Here I tried use array_diff and others but no can get the results as i want
How i can do this for get this results ?
Maybe you could use the array_udiff_assoc() function with a callback
Here you go. It's not the cleanest code I've ever written.
Runnable example: http://3v4l.org/kUC3r
<?php
$array_1=array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2=array("4a-walking","2a-cats");
function getKeyStartingWith($array, $startVal){
foreach($array as $key => $val){
if(strpos($val, $startVal) === 0){
return $key;
}
}
return false;
}
function getMergedArray($array_1, $array_2){
$array_3 = array();
foreach($array_1 as $key => $val){
$startVal = substr($val, 0, 2);
$array_2_key = getKeyStartingWith($array_2, $startVal);
if($array_2_key !== false){
$array_3[$key] = $array_2[$array_2_key];
} else {
$array_3[$key] = $val;
}
}
return $array_3;
}
$array_1 = getMergedArray($array_1, $array_2);
print_r($array_1);
First split the 2 arrays into proper key and value pairs (key = 1a and value = dogs). Then try looping through the first array and for each of its keys check to see if it exists in the second array. If it does, replace the value from the second array in the first. And at the end your first array will contain the result you want.
Like so:
$array_1 = array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2 = array("4a-walking","2a-cats");
function splitArray ($arrayInput)
{
$arrayOutput = array();
foreach ($arrayInput as $element) {
$tempArray = explode('-', $element);
$arrayOutput[$tempArray[0]] = $tempArray[1];
}
return $arrayOutput;
}
$arraySplit1 = splitArray($array_1);
$arraySplit2 = splitArray($array_2);
foreach ($arraySplit1 as $key1 => $value1) {
if (array_key_exists($key1, $arraySplit2)) {
$arraySplit1[$key1] = $arraySplit2[$key1];
}
}
print_r($arraySplit1);
See it working here:
http://3v4l.org/2BrVI
$array_1=array("1a-dogs","2a-cats","3a-birds","4a-people");
$array_2=array("4a-walking","2a-cats");
function merge_array($arr1, $arr2) {
$arr_tmp1 = array();
foreach($arr1 as $val) {
list($key, $val) = explode('-', $val);
$arr_tmp1[$key] = $val;
}
foreach($arr2 as $val) {
list($key, $val) = explode('-', $val);
if(array_key_exists($key, $arr_tmp1))
$arr_tmp1[$key] = $val;
}
return $arr_tmp1;
}
$result = merge_array($array_1, $array_2);
echo '<pre>';
print_r($result);
echo '</pre>';
This short code works properly, you'll get this result:
Array
(
[1a] => dogs
[2a] => cats
[3a] => birds
[4a] => walking
)

PHP Can't get the right format for array

I got stuck somehow on the following problem:
What I want to achieve is to merge the following arrays based on key :
{"Entities":{"submenu_id":"Parents","submenu_label":"parents"}}
{"Entities":{"submenu_id":"Insurers","submenu_label":"insurers"}}
{"Users":{"submenu_id":"New roles","submenu_label":"newrole"}}
{"Users":{"submenu_id":"User - roles","submenu_label":"user_roles"}}
{"Users":{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}}
{"Accounting":{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}}
Which needs to output like this:
[{"item_header":"Entities"},
{"list_items" :
[{"submenu_id":"Parents","submenu_label":"parents"},
{"submenu_id":"Insurers","submenu_label":"insurers"}]
}]
[{"item_header":"Users"},
{"list_items" :
[{"submenu_id":"New roles","submenu_label":"newrole"}
{"submenu_id":"User - roles","submenu_label":"user_roles"}
{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}]
}]
[{"item_header":"Accounting"},
{"list_items" :
[{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}]
}]
I have been trying all kinds of things for the last two hours, but each attempt returned a different format as the one required and thus failed miserably. Somehow, I couldn't figure it out.
Do you have a construction in mind to get this job done?
I would be very interested to hear your approach on the matter.
Thanks.
$input = array(
'{"Entities":{"submenu_id":"Parents","submenu_label":"parents"}}',
'{"Entities":{"submenu_id":"Insurers","submenu_label":"insurers"}}',
'{"Users":{"submenu_id":"New roles","submenu_label":"newrole"}}',
'{"Users":{"submenu_id":"User - roles","submenu_label":"user_roles"}}',
'{"Users":{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}}',
'{"Accounting":{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}}',
);
$input = array_map(function ($e) { return json_decode($e, true); }, $input);
$result = array();
$indexMap = array();
foreach ($input as $index => $values) {
foreach ($values as $k => $value) {
$index = isset($indexMap[$k]) ? $indexMap[$k] : $index;
if (!isset($result[$index]['item_header'])) {
$result[$index]['item_header'] = $k;
$indexMap[$k] = $index;
}
$result[$index]['list_items'][] = $value;
}
}
echo json_encode($result);
Here you are!
In this case, first I added all arrays into one array for processing.
I thought they are in same array first, but now I realize they aren't.
Just make an empty $array=[] then and then add them all in $array[]=$a1, $array[]=$a2, etc...
$array = '[{"Entities":{"submenu_id":"Parents","submenu_label":"parents"}},
{"Entities":{"submenu_id":"Insurers","submenu_label":"insurers"}},
{"Users":{"submenu_id":"New roles","submenu_label":"newrole"}},
{"Users":{"submenu_id":"User - roles","submenu_label":"user_roles"}},
{"Users":{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}},
{"Accounting":{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}}]';
$array = json_decode($array, true);
$intermediate = []; // 1st step
foreach($array as $a)
{
$keys = array_keys($a);
$key = $keys[0]; // say, "Entities" or "Users"
$intermediate[$key] []= $a[$key];
}
$result = []; // 2nd step
foreach($intermediate as $key=>$a)
{
$entry = ["item_header" => $key, "list_items" => [] ];
foreach($a as $item) $entry["list_items"] []= $item;
$result []= $entry;
}
print_r($result);
I would prefer an OO approach for that.
First an object for the list_item:
{"submenu_id":"Parents","submenu_label":"parents"}
Second an object for the item_header:
{"item_header":"Entities", "list_items" : <array of list_item> }
Last an object or an array for all:
{ "Menus: <array of item_header> }
And the according getter/setter etc.
The following code will give you the requisite array over which you can iterate to get the desired output.
$final_array = array();
foreach($array as $value) { //assuming that the original arrays are stored inside another array. You can replace the iterator over the array to an iterator over input from file
$key = /*Extract the key from the string ($value)*/
$existing_array_for_key = $final_array[$key];
if(!array_key_exists ($key , $final_array)) {
$existing_array_for_key = array();
}
$existing_array_for_key[count($existing_array_for_key)+1] = /*Extract value from the String ($value)*/
$final_array[$key] = $existing_array_for_key;
}

Categories