Extract multidimensional array values - php

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

Related

Accessing Array Data in Object

I'm trying to access a piece of data in an array of arrays that (I believe) is in an object (this may not be the right term though).
When I do print_r on this: $order_total_modules->process() I get...
Array (
[0] => Array (
[code] => ot_subtotal
[title] => Sub-Total:
[text] => $49.99
[value] => 49.99
[sort_order] => 1
)
[1] => Array (
[code] => ot_total
[title] => Total:
[text] => $0.00
[value] => 0
[sort_order] => 12
)
)
If I run echo $order_total_modules->process()[1][3];, I should get "0", because that is the 3rd element of the 2nd array... right? Yet, I get an error.
Can anyone help with this?
Even though it is the third element counting from 0, the index is not 3 it is an associative array with the index value:
Available in PHP >=5.4.0:
echo $order_total_modules->process()[1]['value'];
Or PHP < 5.4.0:
$result = $order_total_modules->process();
echo $result[1]['value'];
You cannot access an associative array via an integer index(unless the index is an actial integer).
So in this case use :
[1]['code'] to access what woulde be [1][0] with a 'normal' array.
Try putting it in a var first:
$ar = $order_total_modules->process();
echo $ar[1]['value'];
The second level array is an assoc, which means that the key is not numeric, which means that you need to call the name of the key, hence the 'value'.

Nested array in php

I'm having trouble handling a nested array I get as result from an API. Print_r($result, true); returns an array looking like this (only much longer):
Array
(
[success] => 1
[return] => Array
(
[sellorders] => Array
(
[0] => Array
(
[sellprice] => 0.00000059
[quantity] => 1076.00000000
[total] => 0.00063484
)
[1] => Array
(
[sellprice] => 0.00000060
[quantity] => 927.41519000
[total] => 0.00055645
)
)
[buyorders] => Array
(
[0] => Array
(
[buyprice] => 0.00000058
[quantity] => 6535.77328102
[total] => 0.00379075
)
[1] => Array
(
[buyprice] => 0.00000057
[quantity] => 118539.39620414
[total] => 0.06756746
)
)
)
)
I need to grab the 3 values (sellprice/buyprice, quantity, total) from the first index of both arrays (sellorders and buyorders) and store them in variables ($sellprice, $sellquantity, $selltotal).
The full example php script I'm using can be found on the bottom of this page. Could anyone help me figure this out?
In php, arrays can more or less have infinite dimensions. You can go deeper within an array's dimensions by adding another set of square brackets. For example,
$array['deep']['deeper']['deepest'][0];
Assuming the indexes in the sellorders and buyorders are the same in your array, you could do
$sellprice = $result['return']['sellorders'][0]['sellprice'];
$sellquantity = $result['return']['sellorders'][0]['quantity'];
$selltotal = $result['return']['sellorders'][0]['total'];
The value should look something like this:
$sellprice = $array['return']['sellorders'][0]['sellprice']
You might want to think about how you iterate over these nested arrays in order to pick out all the values. Furthermore, if you have control over the output I might be better to use a different data structure to enable easier processing.
You can access the values of the nested arrays by adding another pair of square brackets with the appropriate index at the end:
$array['outer']['inner'];
It's up to you to transfer this knowledge to your specific array.
If you want to go thru all of those arrays... try this:
for($i=0; $i<count($array['return']['sellorders']); $i++) {
$this_array = $array['return']['sellorders'][$i];
var_dump($this_array); // it includes sellprice, quantity and total for each entity now.
}
use the same method as above for buyorders as well.

PDO fetchAll() primary key as array group key

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(...)))

making array unique with only one value same

I have a array of kind
Array
(
[1] => Array
(
[id] => 1
[username] => test1
[case1] => abc
[case2] => zxc
)
[0] => Array
(
[id] => 1
[username] => test1
[case1] => fdg
[case2] => tyy
)
)
As you can see only id and username is same rest are different. Now i want to make it unique. That if only id is same in inner arrays then also only one value should come either of both.
Can any one tell me how to do this?
Any help will be highly appreciated.
Using the unique data as keys makes this easy:
$unique = array();
foreach ($array as $item) {
$unique[$item['id']] = $item;
}
create a new array in which to push the inner arrays if there is no duplicate
Use this for finding & removing specific unique in array array_unique
You should use 'id', as key for your top array (or 'username'?).

php - replace array elements with another array's elements?

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)

Categories