I have a system where there is a list of items. each has these three fields

id - unique to each item. The index field for the db
name - not unique
date - not unique

I just started using arrays, and am not that proficient. Also, I haven't worked on this for about three to four days, so I can't remember why i did one of these things. I will refer to that later.

So, this array will be opened up on start of the page and set to a session variable. call it array1.

this isn't reflected in the code below, but I will pull a list of items (list1) with the same fields above, reference them againgst the array1 above. Only the ones not in array1 will be displayed.

Each of these will be their own individual forms. when a user clicks on one of the items in this list, it will refresh the page, and add it to array1 which I will use to create list2. Now, I don't want to create duplicate iterations of the same item in array1, which could happen if they hit the refresh button.

So, I have this code below to try an prevent it. But what I get is weird. with 1 item in the list1, I get two iterations can click up two times and get results in list2. I don't know if it is because it is in array1 twice, or if it is going through the foreach function twice.

But to add even more confusion, if I have two items in list2, I can get a couple of different results by refreshing and clicking different combinations of the two items.

I hope that I have described everything properly. The part I can't remember why I created it that way is the structure of the array. And yes, I know I should create a function for adding to the array and call it from the two instances. I am just to impatient right now to get a working model. I will fix that later.

Also, I had put the id in both levels of the array in order to get the results I wanted. If it's not needed, I will remove it.

$array = $_SESSION['array'];

    if (isset($_POST['id'])){
	if (isset($_SESSION['array'])){
	    $exists = array_key_exists($_POST['id'], $array);
	    if ($exists == TRUE){
	     }else{ 
		$array[] = array($_POST['id'] => array( 
                                            "name" => $_POST['name'],
					    "id" => $_POST['id'],
					    "date" => $_POST['date']
							   )
			      );
		    $_SESSION['array'] = $array;
	     }
	}else{
	    	$array[] = array($_POST['id'] => array( "name" => $_POST['name'],
					     "amount" => $_POST['amount'],
					     "id" => $_POST['id'],
					     "date" => $_POST['date']
							   )
			);
		    $_SESSION['array'] = $array;

	}
    }

//this creates the display down below

if(count($array) > 0) {

foreach ($array as $array1) {
    foreach ($array1 as $key=>$array2)
    $display .= "<tr>
                     <td>" . $array2['id'] . "</td>" . 
                     <td>" . $array2['name'] . "</td>" . 
                    "<td>" . $array2['budget'] . "</td>" . 
                    "<td>" . $array2['date'] . "</td>";
    }
}

i think that when I was creating the array I was looking at it from this stand point. I need to search the array to see if the id is present. So, I wanted to set the key as the id. but, I don't think I understand the 'key' concept, because if I went with a single dimension array, wouldn't all of my variables be keys? I need to store the name and date as it pertains to the id. So, I created a multidimensional array to have the id as the key in the 1st dimension, then assign an array to each one of those. each of those arrays would have the name and date in them.

Can anyone help me sort this out? Thanks

Recommended Answers

All 8 Replies

I suggest you go and study PHP Classes. TRUST ME WITH This. It's gonna help yo 1000 ten times fold ;)

i am assuming that you mean the word 'class' as in "classes and objects" and not take a class in PHP, right!?

I understand the broad idea of classes, objects, and oop, but I have yet to get real deep into it. And I should, because I see a lot of others using code that seems to take advantage of them. But in this instance can you tell me why or how classes would be a better alternative compared to the method I am using above (besides the obvious point that my method does not work)?

I just don't understand when to say, "I need class at this point in the code."

thanks. and I will be checking out classes in the meantime.

I have created some demo kind of code.
Check this may be this will give you some info.

<? session_start();
   $array = $_SESSION['array'];

    if (isset($_GET['id']))
	{
		if (isset($_SESSION['array']))
		{
	    	if(!array_key_exists($_GET['id'], $array))
	    	{ 
				$array[$_GET['id']] = array( 
                                            "name" =>'vibha'
							   );	
			}
			 
		}
		else
		{
	    	$addarray = array($_GET['id'] => array( 
                                            "name" =>'vibha'
							   ));	
		    $array = $addarray;							    
		}
		unset($_SESSION['array']);		
		$_SESSION['array'] = $array;
    }
	echo '<pre>';
	print_r($_SESSION['array']);

?>

i am assuming that you mean the word 'class' as in "classes and objects" and not take a class in PHP, right!?

I understand the broad idea of classes, objects, and oop, but I have yet to get real deep into it. And I should, because I see a lot of others using code that seems to take advantage of them. But in this instance can you tell me why or how classes would be a better alternative compared to the method I am using above (besides the obvious point that my method does not work)?

I just don't understand when to say, "I need class at this point in the code."

thanks. and I will be checking out classes in the meantime.

Yes I meant Classes and Objects. You should probably http://www.webninjawannabe.com/tutorials/5-reasons-why-use-object-oriented-programming-in-php

read this. =)

"I just don't understand when to say, "I need class at this point in the code.""
Before you start coding is the best time to decide on how and when to use a class.
That said, classes give you better flexibility and easier ways to handle your data. It also removes much unwanted data querying and php code from your html / display pages. they are clean and precise. Everybody should use classes.
I could help you with a class can you describe your database table? I can make you a simple one with fields as described above in your code.

you could also call

unique_array($array);  
// to only have one instance of any item in that array.
// in your 'validation' code, you could pull all the items out of the array that you currently have and on submission of a new item to array1 as you referred to, if it is already there don't re-insert it into the array.

[begin rambling section]
a new question for you. I understand you want to (or are forced to) use arrays here, you are not familiar with them, better yet, what are you trying to accomplish on your project. why does list 2 need to be pulled and only displayed items not in array1. This could go back to how you are querying your db. since you know what is in array1, why not craft your db query statement for your list to take the id vals from array1 and pull a list where those values are not present and populate your list array data from a better query, and not resort to comparing what is in array1 and list2, to display.
[/rambling]

And also, Using classes and objects are the best practice for any programming language out there. That is learning OOP. That's what they called D.R.Y. Coding. DRY Coding (Don't repeat yourself) makes it easier for the developer to code. Much as like simplifying a math equation. The smaller the formula/code, the better :)

Okay, so I have been researching into your guys' suggestions. I now have a better understanding of classes. It turns out I have been using a similar approach to classes in my coding, but just with functions. A function that I will be using in multiple pages always gets placed into a separate file so that I can use the DRY approach.

I will continue working with classes and try to incorporate it into my code.

But, as for my problem, I have done more research and testing and I know that it has to do with my arrays.

I am using dummy data for now, not attached to a db. Each option has a unique set of values, and each they are id'd 1 and 2. So, I print_r'd my array and this is what I get.


Array ( [0] => Array ( [1] => Array ( [name] => Justin [date] => 09/01/2011 ) ) [1] => Array ( [1] => Array ( [name] => Justin [date] => 09/01/2011 ) ) [2] => Array ( [2] => Array ( [name] => Bob [date] => 09/02/2011 ) ) )

As you can see, there seems to be 3 levels to this array. And I am trying to do my 'array_key_exists' on what appears to be level 2. I had assumed it was on the 1st level. So, when I enter "JJ' the first time with an id of 1, it actually does the exists test and gets a 0. the next time, the array key is 1 so the test returns 'true'.

This also explains why if I choose the 2nd option (bob), I can click it 3 times before the 'exists' test is true (0,1,2).

So, I am augmenting my help request to help me figure out why this is hapenning and how to fix it.

Thanks for the help guys.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.