Checking to see if one variable matches a value in another array. - php

I have a variable called $gID, I also have a multi dimensional array with sets of group values.
eg....
[data] => Array
(
[0] => Array
(
[userId] => 3
[groupId] => 24
[status] => 1
[timestamp] => 2012-08-01 20:09:36
)
[1] => Array
(
[userId] => 3
[groupId] => 25
[status] => 1
[timestamp] => 2012-08-01 20:08:01
)
)
What I need to do is search the array and return true if the status = 1 if the [groupId] = $gID
What would the most efficient way to do this be? Any ideas? I thought of doing it in two foreach loops but thought there must be a better way forward.
Cheers Chris

I wouldn't worry so much about performance at first. Nonetheless, you can do this with one foreach.
// simple boolean function
function search_stuff($arr, $gID) {
foreach ($arr as $item) {
if ($item['gID'] == $gID && $item['status'] == 1) {
return false;
}
}
return false;
}
// sample call
var_dump(search_stuff($arr['data'], $gID));
I suggest making this a function, for flexibility and ease of maintenance. That way if you find a more performant solution, there's only one place to update.

Related

Sorting an StdClass Object Array by the values of another array

I have an StdClass Array. Each object is ordered like this (there are about 50 objects in the array, but I thought I'd just put one to show the structure):
stdClass Object (
[display_name] => Bob Simons
[post_title] => Lesson 1
[meta_value] => 100
[comment_approved] => passed
[c_num2] => 26
[term_id] => 3
)
I have another array that looks like this:
Array (
[0] => 3
[1] => 4
[2] => 5
[3] => 16
[4] => 17
[5] => 18
[6] => 19
[7] => 20
[8] => 21
)
The second array defines the sorting of the first one based on the [term_id] field. So essentially, everything with the [term_id] 3 should be at the top of the array, everything with the [term_id] 4 should be next, all based on that second array.
I am trying desperately to figure out how to do this, I've been looking at usort and the like but at a total loss.
I hope someone can help and will be really grateful.
Try this
$sortedArray = [];
foreach ($order as $termId) {
foreach ($objects as $object) {
if ($object->term_id == $termId) {
$sortedArray[] = $object;
}
}
}
$objects holds your stdClass instances and $order your list with the ordered term ids.
In the case the term_id should always order in an ascending way, you can use usort:
usort($objects, function ($obj1, $obj2) {
if ($obj1->term_id == $obj2->term_id) {
return 0;
}
return ($obj1->term_id < $obj2->term_id) ? -1 : 1;
});

I want to add sub arrays to one single array keep id and value in php

My input array :
Array
(
[0] => Array
(
[id] => 1
[status_name] => Released
)
[1] => Array
(
[id] => 2
[status_name] => Under Construction
)
)
I want the output result :
Array (
[1] => Released
[2] => Under Construction
)
USe sub array id as output array key value and status_name as value array.
This is built into php as array_column. You would have:
$status_names = array_column($data, 'status_name', 'id');
print_r($status_name);
Bonus points on question as I had no idea this existed until looking for an answer for you.
Try the following:
function reOrderArray($input_array)
{
$result = array();
foreach ($input_array as $sub_array)
{
$result[$sub_array['id']] = $sub_array['status_name'];
}
return $result;
}
There might be a built-in php function to do this, array functions in php are quite powerful. I am, however, woefully unaware of one.

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

How do I delete the last array item in a two dimensional array in PHP

I have a two dimensional array and wish to always delete/unset the last array item (in this case Array[3]) in the code sample below, before I put it into a SESSION.
I am still a novice with php and have tried the following with no success.
Any help would be greatly appreciated.
if (is_array$shoppingCartContents)) {
foreach($shoppingCartContents as $k=>$v) {
if($v[1] === 999999) {
unset($shoppingCartContents[$k]);
}
}
}
$shoppingCartContents = Array
(
[0] => Array
(
[productId] => 27
[productTitle] => Saffron, Dill & Mustard Mayonnaise
[price] => 6.50
[quantity] => 3
)
[1] => Array
(
[productId] => 28
[productTitle] => Wasabi Mayonnaise
[price] => 6.50
[quantity] => 3
)
[2] => Array
(
[productId] => 29
[productTitle] => Chilli Mayo
[price] => 6.50
[quantity] => 2
)
[3] => Array
(
[productId] => 999999
[productTitle] => Postage
[price] => 8.50
[quantity] => 1
)
)
Just use array_pop()
$last_array_element = array_pop($shoppingCartContents);
// $shoppingCartContents now has last item removed
So in your code:
if (is_array($shoppingCartContents)) {
array_pop($shoppingCartContents); // you don't care about last items, so no need to keep it's value in memory
}
Your code will fail as you're using strings for keys, not numbers, so the comparison
if($v[1] === 999999)
will never match, and should be checking $v['productId'].
For your use case, rather than looping through the array, you can just pop the last item off:
array_pop($shoppingCartContents);
array_pop removes the last item from an array. It returns that last item, but since you don't want to keep the last item, we're not saving the return value.
Alternatively, if you still wanted to use unset, you could get the last key, and then unset using that.
Finally, as it looks like you've got a true list (i.e. consecutive, numerical indices), you could get away with something like unset($shoppingCartContents[count($shoppingCartContents)-1]);
All that being said, array_pop is the way to go.

Drupal/PHP - Get a specific value in an array

Hi
Suppose I have the code below:
[taxonomy] => Array
(
[118] => stdClass Object
(
[tid] => 118
[vid] => 4
[name] => A
[description] =>
[weight] => 4
)
[150] => stdClass Object
(
[tid] => 150
[vid] => 5
[name] => B
[description] =>
[weight] => 0
)
)
How can I only get the tid number and exclude others, could someone please give me a suggestion?
Thanks you
Assuming taxonomy is key of array $arr, You can fetch tid as,
for example ,
$key = your key //the key for which you want fetch record
$arr['taxonomy'][$key]->tid;
For getting all tid values,
$result = array();
foreach($arr['taxonomy'] as $key=>$value)
{
$value = (array)$value;
if(array_key_exists('tid'), $value)
{
$result[] = $value['tid'];
}
}
print_r($result);
$tids = array_keys($yourArray);
This works because the first level key and the values of subkey "tid" are the same.
Charles Yeung you're requirements aren't clear, you say in the other answer (for Nik) that the taxonomy id is dynamic, equally it seems you have more than one taxonomy node, so can I assume you just want return an array of tid values, right?
Equally you said to rik that you want to check if the key=value, I've no idea what you mean by that, but perhaps you could start here...
$tid=array();
foreach($taxonomy as $key=>$value) {
$tid[]=$value->tid;
}
print_r($tid);
This will give you an array of tid values, if you want to put a condition in there to constrain your output then feel free to do so, problem is your explanation of your requirements aren't clear.

Categories