Need an Array Count On Common Values - php

I am Using PHP and Mysql, Apachhe
I Have an Array
Array
(
[2] => Array
(
[0] => 6
[1] => 2
)
[1] => Array
(
[0] => 6
[1] => 2
)
)
Here The middle container is the Document ID and the final children are userids, Here I am looking for a way to find a method to count the common user ids among all the different Documents. I also need it specified that a particular user id available in which documentids...
could Some one guide me to achieve this?
Thanks in Advance,
OM

$unique_users = array();
foreach ($docs as $doc_id => $users)
{
foreach ($users as $user_id)
{
if (!isset($unique_users[$user_id]))
$unique_users[$user_id] = array($doc_id);
else
$unique_users[$user_id][] = $doc_id;
}
}
echo count($unique_users); // number of users
var_dump($unique_users[1]); // list of documents user_id #1 is in

Add all the ids from the first element to an array. Then continue to loop through the other elements and keep only the ids that are also in the current element.

Related

Confused with session and array

I have a session variable named $_SESSION['items'] that is an array. It stores items in arrays, inside its array. For example:
Array ( [0] => Array ( [0] => 2 [1] => 1 ) )
This show that there is 1 of product 2 in the items array.
Array ( [0] => Array ( [0] => 2 [1] => 1 ) [1] => Array ( [0] => 4 [1] => 1 ) )
This shows that there is 1 of item 2, and 1 of item 4 in the items array..
How so I check if a specific variable is in the items array? For example, i need to know if item 4 or item 1 is in this array so I can show the user a different page depending on if they have this item in their array or not. I get so confused with arrays that I always call undefined offsets and the like.
Figured it out. had a brain fart. thanks
foreach($_SESSION['items'] as $key => $item) {
if($item[0] == $item_id) {
echo "ITEM IS IN HERE";
}
}
//Try using array search good way
Try following this will help you to get the position where found and return nothing if not found
You dont need to loop through.
// this will search $item_id in $_SESSION['items']
$key = array_search($item_id, array_column($_SESSION['items'], 0)); //here 0 is position, see array_search
print_r($key);
if($key){
//yes found at key so that you can easily get that item again without looping
}

how to get value from array with 2 keys

i have array like
Array
(
[1] => Array
(
[user_info] => Array
(
[id] => 1
[name] => Josh
[email] => u0001#josh.com
[watched_auctions] => 150022 150031
)
[auctions] => Array
(
[150022] => Array
(
[id] => 150022
[title] => Title of auction
[end_date] => 2013-08-28 17:50:00
[price] => 10
)
[150031] => Array
(
[id] => 150031
[title] => Title of auction №
[end_date] => 2013-08-28 16:08:03
[price] => 10
)
)
)
so i need put in <td> info from [auctions] => Array where is id,title,end_date but when i do like $Info['id'] going and put id from [user_info] when i try $Info[auctions]['id'] there is return null how to go and get [auctions] info ?
Try:
foreach( $info['auctions'] as $key=>$each ){
echo ( $each['id'] );
}
Or,
foreach( $info as $key=>$each ){
foreach( $each['auctions'] as $subKey=>$subEach ){
echo ( $subEach['id'] );
}
}
Given the data structure from your question, the correct way would be for example:
$Info[1]['auctions'][150031]['id']
$array =array();
foreach($mainArray as $innerArray){
$array[] = $innerArray['auctions'];
}
foreach($array as $key=>$val){
foreach($val as $k=>$dataVal){
# Here you will get Value of particular key
echo $dataVal[$k]['id'];
}
}
Try this code
Your question is a bit malformed. I don't know if this is due to a lacking understanding of the array structure or just that you had a hard time to explain. But basically an array in PHP never has two keys. I will try to shed some more light on the topic on a basic level and hope it helps you.
Anyway, what you have is an array of arrays. And there is no difference in how you access the contents of you array containing the arrays than accessing values in an array containing integers. The only difference is that what you get if you retrieve a value from your array, is another array. That array can you then in turn access values from just like a normal array to.
You can do all of this in "one" line if you'd like. For example
echo $array[1]["user_info"]["name"]
which would print Josh
But what actually happens is no magic.
You retrieve the element at index 1 from your array. This happens to be an array so you retrieve the element at index *user_info* from that. What you get back is also an array so you retrieve the element at index name.
So this is the same as doing
$arrayElement = $array[1];
$userInfo = $arrayElement["user_info"];
$name = $userInfo["name"];
Although this is "easier" to read and debug, the amount of code it produces sometimes makes people write the more compact version.
Since you get an array back you can also do things like iterating you array with a foreach loop and within that loop iterate each array you get from each index within the first array. This can be a quick way to iterate over multidimensional array and printing or doing some action on each element in the entire structure.

Show Can I pull Each Of These Out Of An Array?

I am having trouble pulling elements out of this multi-dimensional array?
Here is my code below:
$ShowTables = $Con->prepare("SHOW TABLES");
$ShowTables->execute();
$ShowTResults = $ShowTables->fetchAll();
If I print_r($ShowTResults); I get this multi-dimensional array:
Array (
[0] => Array ( [Tables_in_alltables] => userinformation [0] => userinformation )
[1] => Array ( [Tables_in_alltables] => users [0] => users )
)
Foreach new table is loaded it adds another dimension of the array. I want to pull each of the table names, out of the multi-dimensional array into a new array which I can use for future plans.
Would anyone have any ideas?
I have tried 1 foreach Loop; but this served no justice.
You want to fetch all results of the first column in form of an array:
$ShowTResults = $Con->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN, 0);
print_r($ShowTResults);
This gives you:
Array (
[0] => userinformation
[1] => users
)
Which I think is what you're looking for.
Another variant (a bit more complicated, but fitting for similar but little different cases) is to fetch the results as function (PDO::FETCH_FUNC) and directly map the result:
$ShowTResults = $ShowTables->fetchAll(PDO::FETCH_FUNC, function($table) {
return $table;
});
A Solution I tried: Perhaps not as other will do, which is in full respect. But Here is mine:
$DatabaseTables = array();
foreach($ShowTResults AS $ShowTResult)
{
foreach ($ShowTResult AS $ShowT)
{
$DatabaseTables[] = $ShowT;
}
}
$DatabaseTables = array_unique($DatabaseTables); //Deletes Duplicates in Array
unset($ShowTResult);
unset($ShowT); // Free up these variables
print_r($DatabaseTables);

Combine array items by name with a separator?

I have the following PHP code which runs a MySQL query and returns the results as an array:
function mysql_resultTo2DAssocArray ( $result) {
$i=0;
$ret = array();
while ($row = mysql_fetch_assoc($result)) {
foreach ($row as $key => $value) {
$ret[$i][$key] = $value;
}
$i++;
}
return ($ret);
}
$compare = mysql_resultTo2DAssocArray(mysql_query("SELECT Temp.School, Temp.Status, Snow.Token FROM Temp
JOIN Snow ON Temp.School = Snow.School"));
The results of this look like:
Array
(
[0] => Array
(
[School] => School Name 1
[Status] => Delayed Two Hours
[Token] => Token1
)
[1] => Array
(
[School] => School Name 1
[Status] => Delayed Two Hours
[Token] => Token2
)
)
Is it possible to combine the Token items by a comma within those arrays if the School item is the same for each?
One thing is that it's possible for there to be more arrays within the global array, with different School names, that shouldn't be grouped but left alone. Basically, is it possible to ONLY group when School is the same. It's also possible for there to be more than two tokens.
SELECT Temp.School, Temp.Status, GROUP_CONCAT(Snow.Token) Tokens
FROM Temp JOIN Snow USING (School)
GROUP BY Temp.School
This isn't completely valid, because the Status column is not aggregated or part of the GROUP BY; however MySQL normally allows it (there's an option to disallow it, I don't remember the name offhand). If there are rows with different Status values, it will pick one of them arbitrarily; you didn't say what should happen with different Statuses.

two php arrays - sort one array with the value order of another

I have two PHP arrays like so:
Array of X records containing the ID
of Wordpress posts (in a particular
order)
Array of Wordpress posts
The two arrays look something like this:
Array One (Sorted Custom Array of Wordpress Post IDs)
Array (
[0] => 54
[1] => 10
[2] => 4
)
Array Two (Wordpress Post Array)
Array (
[0] => stdClass Object
(
[ID] => 4
[post_author] => 1
)
[1] => stdClass Object
(
[ID] => 54
[post_author] => 1
)
[2] => stdClass Object
(
[ID] => 10
[post_author] => 1
)
)
I would like to sort the array of wordpress posts with the order of the ID's in the first array.
I hope this makes sense, and thanks in advance of any help.
Tom
edit: The server is running PHP Version 5.2.14
This should be quite easy using usort, which sorts the array using a user-defined comparison function. The result might look something like this:
usort($posts, function($a, $b) use ($post_ids) {
return array_search($a->ID, $post_ids) - array_search($b->ID, $post_ids);
});
Note that this solution, since it uses anonymous functions and closures, requires PHP 5.3.
One easy solution for this pre-5.3 (the dark ages!) is to do this with a quick loop and then ksort:
$ret = array();
$post_ids = array_flip($post_ids);
foreach ($posts as $post) {
$ret[$post_ids[$post->ID]] = $post;
}
ksort($ret);
You could create a nested looping mechanism to match up the order and ids and rebuild a new post array.
$new_post_array = array();
foreach($id_array as $id) { //loop through custom ordered ids
foreach($post_array as $post) { //for every id loop through posts
if($id == $post->ID){ //and when the custom ordered id matches the post->ID
new_array[] = $post //push the post on the new array
}
}
}
$sortOrderMap = array_flip($postIds);
usort($posts, function($postA, $postB) use ($sortOrderMap) {
return $sortOrderMap[$postA->ID] - $sortOrderMap[$postB->ID];
});
You can simply subtract b from a instead of a from b to sort the other direction

Categories