Not sure how to go about this...
But, I have two arrays, one with updated information, another with outdated information... There are a lot more elements in the second array, but I'm looking to "update" the outdated one with the updated information.
Here's what the arrays look like:
//Outdated
Array (
[0] => Array
(
[anum] => 3236468462
[cid] => 4899097762
[mid] => 1104881401
[na_title] =>
[na_fname] => JOHN
[m_initial] =>
[na_lname] => DOE
[na_suffix] =>
[na_addr1] => 1234 SAMPLE AVENUE
[na_addr2] =>
[na_city] => NORWALK
[state] => OH
[zip] =>
[zip_plus_4] =>
[route] => R002
[dma_code] => 510334
)
)
//Updated
Array (
[1] => Array
(
[0] => YUD990
[1] => 98
[2] => 1234 Sample Avenue
[3] =>
[4] => Norwalk
[5] => OH
[6] => 44857-9215
[7] => 3236468462
)
)
To clarify, I want to:
(1) Match up the value for [7] from the updated array with the value for [anum] in the outdated array, and then update [na_addr1], [na_addr2], [na_city], [state], [zip], [zip_plus_4] in the outdated array with the values for [2],[3],[4],[5],[6] (I know I'll need to split the updated [6] in order to get it to map corrected to the outdated)
Feel like I'm making this very confusing... sorry about that...
Your updated array needs to have matching keys, otherwise there's no way to know how the values should replace the old ones. Then the standard array merge works.
$new = array_merge($outdated, $updated);
Assuming that the structure of the update array will never change, you could just use the code below. (I'm assuming that 'zip' is the first 5 digits and zip_plus_4 is the last 4 digits, but I'm not clear exactly what they're supposed to be.)
$old_array['anum'] = $new_array[7];
$old_array['na_addr1'] = $new_array[2];
$old_array['na_addr2'] = $new_array[2];
$old_array['na_city'] = $new_array[3];
$old_array['state'] = $new_array[4];
$zip_code = explode('-', $new_array[6]);
$old_array['zip'] = $zip_code[0];
$old_array['zip_plus_4'] = $zip_code[1];
I'm not sure why the second array doesn't use its own set of matching keys. It would be more readable and help keeps things consistent. For example, if you end up adding another field, some of the elements could be offset by one, which would just cause headaches. But if the arrays used the same keys, you could use the code below and everything would be fine.
$old_array['anum'] = $new_array['anum'];
$old_array['na_addr1'] = $new_array['na_addr1'];
(etc)
Related
I am trying to create little app that randomly selects a number of chords/notes from a scale but I am having trouble with using the array_rand to get those random values from an array.
I have an array called $scale that looks like this:
Array
(
[0] => f#
[1] => g#
[2] => a#
[3] => b
[4] => c#
[5] => d#
[6] => f
)
I also have an array called $chord_amt:
$chord_amt = array(2,3,4,5,6);
I have used the array_rand function to randomly select one item from the array like so:
$selected_chord_amt = $chord_amt[array_rand($chord_amt)];
Now I want to output whatever number of random chords that this function can produce:
$random_chords = array_rand($scale, $selected_chord_amt);
The problem is, if I print this array, instead of seeing the chord/note values it just shows the keys like this example:
Array ( [0] => 3 [1] => 4 )
How do I get the actual values, so the above output would look like this?
Array ( [0] => b [1] => c# )
Noob question, I know. Sorry.
I'd suggest using a different approach, actually. Using array_rand on this array
$chord_amt = array(2,3,4,5,6);
isn't really needed to generate a random number between 2 and 6. PHP has the rand function for that.
Consider the following instead:
// shuffle the list of chords
shuffle($scale);
// take a slice of it with a random length between 2 and 6
$random_chords = array_slice($scale, 0, rand(2, 6));
Just introduce array_flip with your array_rand:
$random_chords = array_rand(array_flip($scale), $selected_chord_amt);
Prints something like this:
Array
(
[0] => f#
[1] => c#
[2] => d#
)
Like this
$intersect = array_intersect_key($scale, array_flip($random_chords));
Note, I didn't test this, because I'm too lazy to rewrite your arrays, but here's the documentation.
http://php.net/manual/en/function.array-intersect-key.php
http://php.net/manual/en/function.array-flip.php
This is the question as I see it,
How to get a set of items from one array with the keys based on the
values of another array
All random things aside, you have this array
Array
(
[0] => f#
[1] => g#
[2] => a#
[3] => b
[4] => c#
[5] => d#
[6] => f
)
And then you want to get those values based on these keys
Array( 3,4 )
The answer being an array like this
Array('b','c#')
I'm dealing with this array, but the key [row_204] changes each time (ie sometimes it is [row_79] or [row_109]) but all other key names stay the same in this exact structure. I need to get the value of UUID and userID but can't find a solution to get the value by key in that [row_] array.
I need to be able to extract the values and place them in strings, for example,
$uuid =
and so on.
I can't seem to find a similar query and have tried so many variations. Many thanks in advance.
Array
(
[action] => edit
[data] => Array
(
[row_204] => Array
(
[UUID] => 148367FF-FBEB-413D-8495-6B1539BDC5DC
[userID] => 7
[maxPoints] => 7
[awardedPoints] => 6
[Date] => 2017-06-08
)
)
)
If you know there is always only one row_* item in that array, you can just pull the first item (i.e., the only one in your case) off the front of the list with array_shift():
$data = array_shift($array['data']);
print_r($data);
Will give you:
Array (
[UUID] => 148367FF-FBEB-413D-8495-6B1539BDC5DC
[userID] => 7
[maxPoints] => 7
[awardedPoints] => 6
[Date] => 2017-06-08
)
Then you can just deference the keys you want:
$uuid = $data['UUID'];
The easiest would probably be:
$data = current($_POST['data']);
Then just echo $data['UUID'];.
If you need the key for whatever reason:
list($key, $data) = each($_POST['data']);
I want to store the contents of a specific database into an array, grouped by their primary keys. (Instead of the useless way PDO fetchAll() organises them).
My current code:
$DownloadsPDO = $database->dbh->prepare("SELECT * FROM `downloads`");
$DownloadsArray = $DownloadsPDO->execute();
$DownloadsArray = $DownloadsPDO->fetchAll();
Which then outputs:
Array ( [0] => Array ( [id] => 0 [0] => 0 [path] => /xx-xx/testfile.zip [1] => /xx-xx/testfile.zip [name] => Test Script [2] => Test Script [status] => 1 [3] => 1 ) [1] => Array ( [id] => 1 [0] => 1 [path] => /xx-xx/test--file.zip [1] => /xxxx/testfile.zip [name] => New Script-UPDATE [2] => New Script-UPDATE [status] => 1 [3] => 1 ) )
I was considering to use PDO::FETCH_PAIR, however I will be very soon expanding the amount of data I want to be able to use on this script. This works currently, but when I start to expand the amount of downloads and more clients come into play, obviously the way the data is grouped causes an issue.
Is it possible for me to group each array by their primary key (which is id)?
You can just use
$results = array_map('reset', $stmt->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC))
PDO::FETCH_GROUP|PDO::FETCH_ASSOC returns an array of arrays. The first column is used as the key, and then within key is an array of all the results for that key. However, in our scenario each key will only contain 1 row. reset() returns the first element in array, thus eliminating 1 level of nesting.
This should yield what you are looking for :
$results = $pdos->fetchAll(\PDO::FETCH_UNIQUE|\PDO::FETCH_ASSOC);
I decided to just loop through the results with fetch() and enter them into an array as I go along, this is the code I have used and it works just fine:
$DownloadsPDO = $database->dbh->query("SELECT * FROM `downloads`");
$Array = array();
while ($d = $DownloadsPDO->fetch()) {
$Array[$d['id']]["id"] = $d['id'];
$Array[$d['id']]["name"] = $d['name'];
$Array[$d['id']]["path"] = $d['path'];
}
// Outputs
Array ( [1] => Array ( [id] => 1 [name] => Test Script [path] => /xxxx/testfile.zip ) [2] => Array ( [id] => 2 [name] => New Script-UPDATE [path] => /xxxx/testfile.zip ) )
Which uses the primary key (being id) as the name for the array key, and then adds the data into it.
Thought I would add this as the answer as this solved it, thanks to the guys that helped out and I hope this is helpful to anyone else hoping to achieve the same thing.
I'd like to point out the only solution that works for me:
fetchAll(\PDO::FETCH_GROUP|\PDO::FETCH_UNIQUE|\PDO::FETCH_ASSOC);
Beware that this will strip the first column from the resultset. So the query must be:
SELECT id_keyname AS arrkey, id_keyname, .... FROM ...
I'm still suggesting you to loop using fetch() method. Otherwise, you can use array_reduce() to iterate over the array. A sample on codepad is here.
The code(in human readable form) will be:
$myFinalArray = array_reduce($myInputArray, function($returnArray, $temp) {
$temp2 = $temp['id'];
unset($temp['id']);
$returnArray[$temp2] = $temp;
return $returnArray;
}
);
So, my question is; is it possible for me to group each array by their
primary key (which is id)
Off course, you have 2 options here: Either to change the query or parse a result-set.
So, I'm sure you don't want to change query itself, so I'd go with parsing result-set.
Note:
You should use prepared SQL statements when they make sense. If you want to bind some parameters then its OKAY. But in this case, you only want get get result-set, so prepare() and fetch() will be kinda overdo.
So, you have:
Array ( [0] => Array ( [id] => 0 [0] => 0 [path] => /xx-xx/testfile.zip [1] => /xx-xx/testfile.zip [name] => Test Script [2] => Test Script [status] => 1 [3] => 1 ) [1] => Array ( [id] => 1 [0] => 1 [path] => /xx-xx/test--file.zip [1] => /xxxx/testfile.zip [name] => New Script-UPDATE [2] => New Script-UPDATE [status] => 1 [3] => 1 ) )
And you want:
Array( [id] => Array('bar' => 'foo') ....)
Well, you can do something like this:
$stmt = $database->dbh->query("SELECT * FROM `downloads`");
$result = array();
foreach($stmt as $array){
$result[$array['id']] = $array;
}
print_r($result); // Outputs: Array(Array('id' => Array(...)))
I have something like this
Array
(
[0] => stdClass Object
(
[CustomerID] => 14
[Email] => joe.blogs#example.com
[LastName] => Blogs
[BirthDayOfMonth] => 29
[Gender] =>
[Occupation] =>
[SendSpecialOffers] => 1
[SendReminderNotes] => 1
)
[1] => stdClass Object
(
[CustomerID] => 1460
[Email] => example#example.com
[LastName] => Example
[BirthDayOfMonth] => 5
[Gender] => F
[Occupation] =>
[SendSpecialOffers] => 1
[SendReminderNotes] => 1
)
);
I would like get Email address of each separated by commas, something like this
'joe.blogs#example', 'example#example.com'
I know i could iterate it through foreach but i got a really big list, is there anyway to do it faster? thanks
Now, how can i remove the indexes based some email addresses?
You can do this with array map and a function but this will also iterate your array
echo implode(',',array_map('getEmail',$array));
function getEmail($obj)
{
return $obj->Email;
}
The simplest solution would indeed be a foreach() to iterate over all the items of your array ; adding, for each item, the email to a another resulting array.
Maybe you could replace the foreach by a call to array_walk(), but it probably wouldn't change much :
You wouldn't loop in PHP, as array_walk is coded in C (could be a bit faster than foreach -- not sure, though)
But a function would be called for each item, instead of just a couple of PHP instructions.
You'd have to benchmark, to see if there is a significant difference in your specific case -- but I personnaly would go for the foreach, without thinking much more.
array_filter is best..see the examples on manual
Thought I will point out first that I have looked around on Stackoverflow and the internet already and although they are plenty of examples none of them are explained into such a way for me to understand how to convert the code to work with my array structure.
I believe I need to use one of the functions uksort or uasort but unsure on this as well.
My array looks like the following.
Array
(
[0] => Array
(
[Result] => Array
(
[id] => 260
[event_id] => 72
[year] => 2010
[york_score] => 27
[york_points] => 0.0
[lancs_score] => 51
[lancs_points] => 4.0
[winner] => L
[confirmed] => Y
[updated] => 2010-05-01 16:10:03
)
[Event] => Array
(
[id] => 72
[sport_id] => 25
[event_title] => 1st Team
[Sport] => Array
(
[id] => 25
[sport_title] => Netball
)
)
)
And where its [0] means it continues on.
I need to sort all of the arrays [0,1,2,3,...] by the sport_title key found in [Event][Sport]
Does anyone know how to create a sorting function to do this?
Some explanation of how the function is working would also be helpful if I later need to adapter/alter the code to work else where on my site.
Where $array is the name of the array which holds the array you posted in your question.
function sort_multi($item_1, $item_2)
{
// strcmp looks at two strings and, based off the characters' and their order,
// determines which one is numerically greater. When this function returns a
// negative, for example, it means the first item it's comparing is less that the
// second item (ef and eg, for example). The usort function then rearranges
// the array based off these comparisons.
return strcmp($item_1['Event']['Sport']['sport_title'], $item_2['Event']['Sport']['sport_title']);
}
usort($array, 'sort_multi');