I'm building a 3 page submission form, and I'd quite like all of the $_POST results to be stored in a single session variable.
So page 1 starts by setting up the array and adding the first lot of post data:
$_SESSION['results'] = array();
$_SESSION['results'] = $_POST // first lot of post data
This works great and returns an array like:
Array
(
[name] => bob
[address] => 1 foobar way
[age] => 100
)
So when I get the resuts from page 2, I want to simply append them to the existing array without invoking a new array+key
array_push($_SESSION['results'], $_POST); //second lot of post data
To get something like this:
Array
(
[name] => bob
[address] => 1 foobar way
[age] => 100
[job] => rubbish php dev
[salary] => 1000
)
But instead I get:
Array
(
[name] => bob
[address] => 1 foobar way
[age] => 100
[0] => Array
(
[job] => rubbish php dev
[salary] => 1000
)
)
Even more annoying is that I'm sure I had this working properly before I tweaked the code. What am I doing wrong?
You can also use the + operator:
$combined = $_SESSION['results'] + $_POST;
array_merge() is the function you're after.
array_merge() is your answer see http://php.net/manual/en/function.array-merge.php
You have to use array_merge(), look at this: array_merge()
Related
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'.
Im trying to put multiple posts into one session. Heres the line of code that i use to do it.
$_SESSION['answers'][] = array_push($_SESSION['answers'], $_POST);
As i do so, the following array comes out once i try to add the second array to the session:
Array
(
[0] => Array
(
[checkbox] => Optie 2
[category] => Dieren en natuur
[subcategory] => Wilde dieren
[vraagid] => 116
[type] => 3afbeeldingen
[media] => image
[submit] =>
)
[1] => Array
(
[checkbox] => Optie 1
[category] => Dieren en natuur
[subcategory] => Wilde dieren
[vraagid] => 117
[type] => 3afbeeldingen
[media] => image
[submit] =>
)
[2] => 2
)
I am talking about the last array,
[2] => 2.
This is automattically added. Now when i try to get another array in to the session, it gives me the same issue, it adds the correct array, with checkbox and other vars, but also makes a
[4] => 4
Is this an issue with the array_push function? Because the array that i push is correct, i already checked that.
Either add the value to your array:
$_SESSION['answers'][] = $_POST;
or use array_push
array_push($_SESSION['answers'], $_POST);
You try to do to much at once :)
Won't it work, when you just do:
array_push($_SESSION['answers'], $_POST);
or
$_SESSION['answers'][] = $_POST;
array_push() is basically the same as $array[] = .... array_push() returns the new number of elements in the array, so basically you are adding the new element to your array and then you are adding the amount of elements in the array to the array again (hence the 2).
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 an array like this:
Array
(
[0] => Array
(
[id] => 68
[type] => onetype
[type_id] => 131
[name] => name1
)
[1] => Array
(
[id] => 32
[type] => anothertype
[type_id] => 101
[name] => name2
)
)
I need to remove some arrays from it if the users has permissions or not to see that kind of type. I am thinking on doing it with a for each, and do the needed ifs inside it to remove or let it as it.
My question is: What's the most efficent way to do this? The array will have no more than 100 records. But several users will request it and do the filtering over and over.
use this 1 simple and easy
foreach ($display_related_tags as $key => $tag_name) {
if($tag_name == $found_tag['name']) {
unset($display_related_tags[$key]);
}
}
Use in_array() function so that you could find the array that you would want to remove.
Then use unset() function to unset the array or variable that you would want to remove from your existing array.
On this way, you don't need to loop your array over and over.
I think you understand the basics of PHP and stripping the array.
What you could do after stripping the array store it in a session for re-use after a page-refresh or loading of a different page. That way, you only have to do it once.
See: http://www.php.net/manual/en/function.session-start.php
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