Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
 
  HOME    TRACKER    PHP




Counting Items In An Array Having X Attribute


I want to randomly select 5 cards from a standard playing card deck and count how many of each suit are returned:

[connect]
$sql = "SELECT * FROM cards ORDER BY RAND()LIMIT 5";
$result = mysql_query($sql);
while($cards = mysql_fetch_array($result)) {

$value = $cards["card_value"];
$suit = $cards["card_suit"];
$image = $cards["card_image"];
--------

Using count() within the loop returns a count of 1 since each card can only be of one suit. I tried using something like this:

$spades = 0;
if($suit='spades') {
$spades = $spades+1;
}

and I tried a foreach statement to count within the loop which always returns a count of 1.

Would someone be so kind as to point me in the right direction?




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
How Many Items Are In An Array?
I dont know how many values there are in my array after it's been split.. is there a command? array_count_values doesnt do what I need sadly.

Display All Array Items
How do I display all the items within an array? Also, how do I delete a particular item from an array?

Compare Items In An Array...
I have been getting on fine with basic coding until I stumbled accross a problem. I cant seem to figure out how to check to see if a value in one array is in another array - and if so just simple report back "true" or "false".

Lets call the two arrays LOCKS and KEYS. Doing a print_r($locks) would give: Code:

How Do I Delete Items From Array?
I can add several items to the basket, but how do I delete one from the basket? I want to delete any of the added items. Here is my code for creating the array and adding items to it.

// creating the array
$item = array();
$item['id'] = "1";
$item['price'] = "100";
$item['quantity'] = "1";

// add item
$_SESSION['basket'][] = $item;

Counting An Array
i need to count 2-dimensional array $this->myarray[$a][$b] after $a, my code PHP Code:

Adding Only Unique Items To An Array
I've made a small code snippet that adds a new item ($value = $_GET) to an array in a cookie. My main question is in the title of the post, and I have a related one: How do I delete a specific value from the array and shift all the other values down to fill its place? Will this happen on its own? And one more: Using this code I display the array values in descending order;

foreach ($_COOKIE['best'] as $name => $value) {
$best = urlencode($value);
echo //insert code here
}
}

Is there any way to display this in ascending order?

Counting Elements In A 2D Array
How can I count the number of items in a multidimensional array, this is what I am using but there must be a more efficent way
// contents is my 2D array
$len=count($contents);
if($len == 0)
echo "message";
else
{
// need to go thru and count our number of elements in the array
$counter = 1;
reset($contents);
while(next($contents))
$counter++;

Counting Numbers In Array
Assume I have an array which contains the following numbers:
2
5
7
9

How would I go about adding them to eachother?( e.g. in this case 2+5+7+9 would be 23)

Trying To Return Mysql Array Items From Function
I am writing a calendar script which returns events, holidays etc.. from MySQL for days with events. This was easy BUT then I tried to return multiple events on some days and thats where I am stuck.

I found some examples of returning arrays from functions from functions but they all use some form of array(Ƈ',ƈ',Ɖ') and then use a for loop... I am using mysql_fetch_array so this does not seem to work... First, here is some of the code from the function where I am returning the value: PHP Code:

Check If Any Items In An Array (php) Is In A Table (mysql).
I want to check if any of the items in a PHP array exist in a MySQL
table. What is the best way to do this with making repeated calls to the
database for each item?

Actual application is:

I have an array (in PHP) of serial numbers of units about to be
shipped.I want to check the ship record (a table in a MySQL database) to check
if that serial number has been used before.

According to our quality policy we never reuse serial numbers, serial
numbers are unique. So prior to printing the packing slip I want to
warn the shipping guy/gal a serial number may be incorrect.

I could brute force it and increment through the "to be shipped array"
and check each item against the table. But that is, as I said brute
force, and I am having to be concerned with system speed lately.

Remove Items From Array, Shift Positions
Hey, lets say I have:

x = array("red", "blue", "green", "yellow", "orange", "grey");

Now lets say I have a loop that prints out what is in the array. I want to be able to remove blue green and yellow, but effectively shift down everything else in the array (in this case orange and grey) so that orange is now positioned relative to where blue was and grey is where green was. By this I mean x[1] = "blue" and x[2] now quals "grey".

How can I do this?

Counting The Number Of Elements In An Array
I have 10 text field form elements and have put them in an array by giving them the same name - ie name="att_name[]"

When the user submits - I then loop through the array and print results :

foreach ($att_name as $value) {
echo $value.'<br/>'}

This works fine but I want to count the number of elements in the submitted array. So of the 10 textfields - if the user fills out 5 of them and submits - I want to get an element count of 5 -

I have tried using count($att_name) but that returns a value of 10 - I'm assuming it counts each textfield as an element. But I need to know how many elements are in the array that is submitted.

Counting The First Dimension Of Two Dimensional Array
I'm trying to count just the items in the first dimension of a two dimensional array.
It seems like: PHP Code:

XML - Sorting By Attribute
I'm not sure whether this is a question about php or xml or what to be honest - a poke in the right direction would be much appreciated...

I'm storing news articles in XML format.

newsitems.php which contains the XML looks like this; ....

Domxml_new_doc - Can I Add Encoding Attribute?
I've got a question about adding encoding attribute to my DOM XML Document?

I'm from Poland and we use extended latin alphabet - I'd like to use
iso-8859-2 Polish charset

e.g.:
<?xml version="1.0" encoding="iso-8859-2"?>

is there such posibility in DOM XML?

LDAP And TelephoneNumber Attribute
Anyone have a problem with PHP returning the telephoneNumber attribute empty while all the other attributes return just fine. Someone had the same exact problem on phpbuilder but it was never solved. Apparently it holds true for facsimileTelephoneNumber also. Any ideas?

A '<' Character Cannot Be Used In Attribute 'href', Except Through <[xml]
The following embedded snip it of PHP code won't validate using xhtml 1.0 strict. When validating I get the following error:

A '<' character cannot be used in attribute 'href', except through <[xml] Code:

href="/_Director/forms.php? <?PHP create_request_query('AskQuestions', 'AskQuestions'); ?>" Any idea what's wrong?

Populating An Auto_increament Attribute
I have just designed a BD. there are companies with auto increament which are integer. When I try to populate it after i tool value from another form and try to insert it into a table i recieve an error! I don't ask the companyID value from user as it is auto increament. Don't tell me to put NULL for that entry as it didn't work as well! Code:

SimpleXML Parsing By Attribute Value
I have an existing XML data set and would like to parse it with PHP5 based on the value of an attribute (any attribute!). I don't want to convert all my data from an attribute-heavy structure to a more proper element-based structure if I don't have to because of the javascript I am using on the client side. Listed below is the XML structure and PHP code I have been testing.

My existing data structure looks like this:
<gallery>
<photos>
<photo
path = "sunflower01.jpg"
width = "500"
height = "375"
thumbpath = "sunflower01.jpg"
thumbwidth = "125"
thumbheight = "94">
</photo>
</photos>
</gallery>

The script is here:

<?php
$xml = simplexml_load_file("pictures.xml");
$image = $xml->xpath("/gallery/photos/photo[@path='sunflower01.jpg']");
echo $image[0]->photo@thumbpath;
?>

Sort A Group Of Nodes By Attribute? How?
I have the following XML file:

<?xml version="1.0" encoding="iso-8859-1"?>
<items>
<item line="2">all that glitters is gold,</item>
<item line="1">Theres a lady thats sure,</item>
<item line="3">and she's buying a stairway to heaven</item>
</items>

To output this code Im using the following PHP:

$xmldoc = domxml_open_file('stairway.xml',
DOMXML_LOAD_DONT_KEEP_BLANKS);
$node = $xmldoc->document_element();
if ($xmldoc->has_child_nodes()) {
$node = $node->first_child();
$endwhile = false;
while ($endwhile != true) {
echo $node->get_content() . "<br />";
if ($node->next_sibling()) {
$node = $node->next_sibling();
}else{
$endwhile = true;
}
}
}

This does what it supposed to do except I want to ensure that it
outputs nodes ordered by 'line' attribute. The obvious answer would be
to put them in order in the XML file and the above example is very
simple so that you get the point, the real life example however will be
much larger and encase anyone put something in the wrong order it would
muck up my presentation. How could I adapt my code above to allow my
nodes to be sorted? I dont mind the nodes being out of order in the
physical file (stairway.xml) but when they are output using my script,
I want them to be ordered.

Accept Form Attribute Not Working
I cannot get my accept attribute working properly inside either my form, or my input tag. W3schools says that accept is supposed to go inside the input tag, but msdn says it goes in the form tag. I need it for an upload form I'm making, I want to only allow application/octet-stream type files, so I put this as my opening form tag:

<form enctype="multipart/form-data" accept="application/octet-stream" action="{$_SERVER['PHP_SELF']}" method="POST">

But I can still upload music, text files, and movies.  What gives?

After I Load An XML File, Can I Sort It By Node Attribute
After loading an xml file, is it possible to sort it by attribute?

For example, I have the following xml file:

<xml...
<diary>
<entry date="2005-01-01">I went to the park</entry>
<entry date="2005-01-03">Sold the car today</entry>
<entry date="2005-01-02">Went for a stroll</entry>
</diary>

When I go to load this using PHP, I would use some this similar to
this:

$xmldoc = domxml_open_file('diary.xml', DOMXML_LOAD_DONT_KEEP_BLANKS);

$node = $xmldoc->document_element();

Before I go storming through the xml tree outputing along the way, can
I sort it by (in this case) date?

Php-4.4.0 And Test.wsf = Error: The Value For The Attribute Is Not Valid: Language
We need to use version php-4.4.0-Win32 because one of the portal software
doesn't support version php-5.0.5-Win32. We cannot get the PHP setup part
working. Here is the error message:

Windows Script Host

Script: C:kits est.wsf
Line: 3
Char: 11
Error: The value for the attribute is not valid: language
Code: 80040049
Source: Windows Script Host

Here is the code from the install.txt

To test if ActiveScript is working, create a new file, named test.wsf (the
extension is very important) and type:

<job id="test">

<script language="PHPScript">
$WScript->Echo("Hello World!");
</script>

</job>

Save and double-click on the file. If you receive a little window saying
"Hello World!" you're done.

Everything works fine using php-5.0.5-Win32.

Simplexml And Attributes With A Namespace In Front. How Do You Getthe Attribute?
Here's a bit of xml code that works.

<?php

$string =
"<?xml version="1.0" standalone="yes"?>
<world>
<people xmlns:ss="http://crap">
<person id="5">John Doe</person>
<person id="2">Susie Q. Public</person>
</people>
</world>";

$xml = simplexml_load_string($string);
print "<pre>";
print_r($xml);
print "</pre>";

foreach($xml->people->person as $p)
foreach($p->attributes() as $a =$b)
{
print "$a =$b<br />";
}

// prints out
// id =5
// id =2
?>

Now what if I change the first person to this
<person ss:id="5">John Doe</person>

Anyone know how to get the id?

This is a question that is pertinent to an excel .xml file as
you'll get lines like this
<Cell ss:Index="3">stuff</Cell>

btw: there is a guide on ibm that tells you how to do this with php
and dom. I'm just wondering if there's a way to do it with simplexml.

Related Items
I noticed a lot of websites show "Related Items" on each product page. I want to know how usually do you implement it. Should I add a field in the mysql table to hold the "Related Items" information? What's the best solution?

Get ID Of Deleted Items
I wonder if there is anything similar to "mysql_insert_id();"
for deleted/updated id's?

If i do a query and DELETE WHERE text_field="",
can i get the id's of the fields that were deleted?

Add/Delete Items
I have the following code, that displays a message whether a users shopping cart contains items or not. How do I add/delete items from the shopping cart, upon the appropriate product link being clicked? If a items is already in the cart, how do I display a message notifying the user? Code:

Favorit Items
i have many tables with different data structure due, am  making a service which will allow users to add itimes to thier "favorit items" tables
I thinked to use the table names as a hidden filed, like if the table name is "hotel" and the user added a hotel to his favorit items , the hidden fild will be hotels, and then pass that field as a variable then use it in a query to get the hitel data, does this adea work? or there is a better way ?

Using If Empty With Two Items
I am trying to say if $_Post and $_Session are empty set the variable $dcparent to equal 1, but it doesn't like what I am doing. 

if(isset($_POST['dcparent'])) {
$dcparent = mysql_real_escape_string($_POST['dcparent']);
}

if(isset($_SESSION['dcparent'])) {
$dcparent = mysql_real_escape_string($_SESSION['dcparent']);
}

if(empty($_POST['dcparent']) && (empty($_SESSION['dcparent'])) {
$dcparent = 1;
}

Counting
I have looked up count() and sizeof() but they're not quite what I'm looking for ...

I'd like to open a text file using PHP, which I know how to do, and count the number of instances of a string, which I don't know how to do!

There are in particular 6 types of string. I'd like to count the total of each and use each total to form the data for a graph.

This is irrelevant to my query, but for anyone interested, I'm using the JavaScript graph builder library at:

Row Counting
I'm using LIMIT in my SQL query to create a paging effect for a gallery. I need to count the total number of rows in the table, but I'm having a problem.  Instead of giving the number of rows, it simply returns the word "Array". Code:

Counting
I have the following query

SELECT COUNT(*) as Num FROM files GROUP BY categoryid

The problem is that if I run this query in phpmyadmin, I get a total of 4, which is right. But if I run this query within a php page, I only get 2 as a result.

Can anyone tell me why I get a different result?

Counting
for ($n=0;$n<1000;$n+50)
This does not seem to give a result of 0, 50, 100 for $n - it seems that when I use this for $n it goes 1,2,3,4 etc.

What is wrong with it?

Multiple Cart Items
I've created a shopping cart application using php 4.06 and postgres. a problem i had was that when i added the same item twice it was adding an extra item as opposed to adding the quantities together. i did manage to sort this out to an extent but my only solution means using a block of code for each item which has made my script very long and i'm pretty sure has made the script somewhat unreliable. I would appreciate it greatly if someone could offer a solution to this, this is my code for adding items to the cart: PHP Code:

Finding @ In A String, And Other Items
Ok - I want to check a string for @ in it (Im checking to see if a string
that should contain an email holds a @ )

How would I go about this? preg_match? ereg? strstr? Examples?

Also - how would I find any non alpha numeric characters in a string so I
can give the user an error message. I dont want any characters besides
alpha-numeric in the strings.

Multiple Items Of Same Name In Session?
I have a shopping cart where I can add tshirt designs to the cart. The designs are added to a php session object called cart. The object 'cart' consists of the design name, color and the quantity.

The probem is that if someone adds the same design to the cart again then it just increments the quantity of the existing design with the same name instead of adding another instance of it to the cart. How can I have multiple instances of the same design with the same name in the cart at the same time.

One thing I thought of was to append some sort of incrementing id to the design name before it is added to the cart. Thus the next time the design is added it would have a new id appended and the resulting name would be different.

Dynamic Form Items
I am trying to create A form that its fields will depend on a
form menu.
for example.
/***********************************************/
<form name="form1" method="post" action="">
<select name="select">
<option value="1">option 1</option>
<option value="2">option 2</option>
<option value="3">option 3</option>
</select>

Text field 1<input type="text" name="textfield">
Text Field 2<input type="text" name="textfield2">
Text Field 3 <input type="text" name="textfield3">
Text Field 4 <input type="text" name="textfield4">

<input type="submit" name="Submit" value="Submit">
</form>
/***********************************************/
When the option 1 is selected only the textfields 1 and 2 to appear,
when option 2 is selected only textfields 1 and 3 to appear and so on... any
combination I would like.

I tried puting the textfields in "if" statments but i don't like it. its too
messy PHP and HTML code.
Any Ideas of how this could be done better ? If someone did something
similar before and has a relative link it would be good as well.

Number Of Items In A Cart
I am working with a session and a 'cart' (note that I do not really know what I am doing though).

I was wondering if there is some easy way (function) to work out how many items I have in my 'basket' / 'cart', because then I could
call this function from anywhere to show the user just how many items are on order



Only Allow X Number Of Items To Be Checked
I have a function that renders out tag categories, and then all the tags within said category. Each tag has a checbox beside it, i am wondering if it's possible to only allow a user to check 4 tags. Here is the function: Code:

Display Items Using Checkbox
i have a page where in it lists all job items on a table and each item has a checkbox
so when i check one or more items when i click the post button it should display the job items on this post page. my problem is, my post page is not working. Code:

Count Of How Many Items Are In Database
I am wanting to create an select menu for displaying the order of the item
on a page. I am guessing that I need to get the count of how many items are
in the db and them put them into a select menu.

Does anyone know how to do this or can point me in the right direction?

Changing Items After A Date
What I have is a table (code below) and it is for an events page. What I want is after the date has gone, it changes the whole row to grey. ( #666666 ). Code:

Deleting Items From A List
When i click one of the delete buttons, the form submits, but nothing happens. I'm pretty sure i'm doing something stupid with the form buttons, but I've been staring at it too long...any takers? Code:

Multiple Items In Foreach()
Can someone tell me what im doing wrong with the code bellow please? I get print_ticket called lots of times, with 1 as the hash,name,ticket_no responce.

(i have chequed that the query is returning the right results).

$return = pg_query($pg_connection, $query);
        $data   = pg_fetch_array($return);                   

foreach ( $data as $temp ) {
   
echo print_ticket ($temp['hash'],$temp['name'],$temp['ticket_no']);   
}

Seperating Search Items
When conducting a php sql search i get some great results, however i want to expand my results so that when multiple search terms are added it will display all relevant fields.

$query = "SELECT * FROM Mixes WHERE dj LIKE '%$var%' OR event LIKE '%$var%' OR tracklist LIKE '%$var%' OR date LIKE '%$var%' ORDER BY event ASC";

From the above search i can only get single results from 1 field. I want to be able to seperate the search term into individual items that can be referrenced in the database.

So for example i search for a dj name and also an event they play at i get zero results, however if i search for them individually i get the results i want.

How do i expand the code to display the result of both the dj and the event or any of the other fields?

I presume that i need to be able to set each search item into an individual variable and then use them to search.

Counting Rows
I need to get the number of rows in a table.

This is the query I'm using at the moment:

$query = "SELECT COUNT(*) from mytable";
$result = mysql_query($query) or die ...;

What php function may I use to get the number and in which way?

I tried with

$num = mysql_num_rows($result);

but nothing.

Counting Characters
Just a silly little problem i'm not entirely sure how to tackle. I'm wanting to search through a string for a certain character and then count the number of times it appears (or return false if it doesn't locate the character).

Counting Matches
This is really more of a MySQL question than PHP per se, but the only
MySQL group my newserver carries seems to be pretty quiet, so I
thought I'd ask here.

What I am trying to do is determine the number of terms which match a
field in the database where an initial string of multiple words has
been broken up into single terms and the SQL statement is built by
looping through each term separately, something like this:

$original_string = "this is a test string"

// code to remove stop words/common terms leaves

$trimmed = "this test string"

// this is then exploded at the space into an array of its constituent
words. This array is then looped over to pass each word to an SQL
query thus

$SQL = "select * from main where"
while(there are terms){
$SQL .= "Title like '%" . $term . "%' OR"
}

// this would lead, using the above example, to an SQL query which
looks like this:

$SQL = "SELECT * FROM main WHERE Title like '%this%' OR Title like
'%test%' OR Title like '%string%'

What I need to do is to check how many of the terms actually match
something. Is there any way, either in MySQL or with the result array
in PHP, to determine this?

Counting Files In Dir ?
Is it possible to count the files in a certain server dir, and show the filenames ?


Copyright © 2005-08 www.BigResource.com, All rights reserved