Solved

Swapping Information In PHP arrays

Posted on 2011-02-28
20
812 Views
Last Modified: 2013-11-19
What I need is to:

- take the information from array 1
- remove it from array 2
- then ADD it OR take from array 3 (this of course depends on array 1)

I also have to keep in mind that array 1 could be empty thus needing to empty array 2 and IF the information is in array 3 then remove it

array 3 is the main array that I will update the database row which will in turn display the correct check boxes checked or not

Thank you for reading, I hope you can help me.
Array //#1 this is the submitted information
(
    [0] => 103100000
    [1] => 103200000
    [2] => 103400000
    [3] => 103500000
    [4] => 103700000
)

Array //#2 all possible choices
(
    [0] => 103100000
    [1] => 103200000
    [2] => 103300000
    [3] => 103400000
    [4] => 103500000
    [5] => 103600000
    [6] => 103700000
)

Array //#3 currently stored in database / marks the check boxes "checked" 
(
    [0] => 103100000
    [1] => 103200000
    [2] => 103300000
    [3] => 103400000
    [4] => 103500000
    [5] => 103600000
    [6] => 103700000
)

Open in new window

Capture.JPG
0
Comment
Question by:phpretard
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 10
  • 8
  • 2
20 Comments
 
LVL 34

Expert Comment

by:Beverley Portlock
ID: 35002179
Look at http://uk2.php.net/array_intersect and http://uk2.php.net/manual/en/function.array-diff.php

I'll see if I can get you an example based on your data
0
 

Author Comment

by:phpretard
ID: 35002208
I have found this to show me the difference in the arrays.

so the question left is how do I get the information from array 4 to Remove or Add the information to  array 3?



if(empty($_POST['page'])){$array1 = array();}else{$array1 = $_POST['page'];}
$array2 = $_POST['page_array'];
$array3 = explode(",", $_POST['existing']);
$array4 = array_diff($array2,$array1);

echo "<pre>";
print_r($array4);
echo "</pre>";

Open in new window

0
 
LVL 34

Expert Comment

by:Beverley Portlock
ID: 35002223
Something like this.... and look at http://www.php.net/array_merge for combining the arrays

<?php

$arr1 = array
(
    0 => 103100000,
    1 => 103200000,
    2 => 103400000,
    3 => 103500000,
    4 => 103700000
);

$arr2 = array
(
    0 => 103100000,
    1 => 103200000,
    2 => 103300000,
    3 => 103400000,
    4 => 103500000,
    5 => 103600000,
    6 => 103700000
);

$arr3 = array
(
    0 => 103100000,
    1 => 103200000,
    2 => 103300000,
    3 => 103400000,
    4 => 103500000,
    5 => 103600000,
    6 => 103700000
);

print_r( array_diff( $arr2, $arr1 ) );

Open in new window

0
Setting up LaraDock for Laravel

Learn how to set up LaraDock in a Laravel project - LaraDock gives us an easy way to run a Laravel application using Docker in a single command.

 
LVL 34

Expert Comment

by:Beverley Portlock
ID: 35002230
Just seen you latest post. What is the criteria to decide whether data is added or removed frm the final array. I'm not clear on that bit
0
 

Author Comment

by:phpretard
ID: 35002321
I select or deselect a checkbox:

$array1 is: type='checkbox' name="page[]"
$array2 is: type='hidden' name='page_array[]'
$array3 is: type='hidden' name='existing[]' <-- from database
$array4 = array_diff($array2,$array1);

The most important element is $array3 as it will update the database with the new numbers
if(empty($_POST['page'])){$array1 = array();}else{$array1 = $_POST['page'];}
$array2 = $_POST['page_array'];
$array3 = $_POST['existing'];
$array4 = array_diff($array2,$array1);

echo "<pre>";
print_r($array1);
echo "</pre>";

echo "<pre>";
print_r($array2);
echo "</pre>";

echo "<pre>";
print_r($array3);
echo "</pre>";

echo "<pre>";
print_r($array4);
echo "</pre>";

prints in this order:

Array
(
    [0] => 103100000
    [1] => 103200000
    [2] => 103600000
    [3] => 103700000
)

Array
(
    [0] => 103100000
    [1] => 103200000
    [2] => 103300000
    [3] => 103400000
    [4] => 103500000
    [5] => 103600000
    [6] => 103700000
)

Array
(
    [0] => 103100000,103200000,103300000,103400000,103500000,103600000,103700000
)

Array
(
    [2] => 103300000
    [3] => 103400000
    [4] => 103500000
)

Open in new window

0
 
LVL 34

Accepted Solution

by:
Beverley Portlock earned 500 total points
ID: 35002441
OK I'll have a look at it. As an aside you might find this technique useful... before each checkbox declare a hidden field with exactly the same name as the checkbox following it but with an "off" value. That way when you do your submit every checkbox is represented, not just those with an "on" value. It culd eliminate the need for one of your arrays.

     <input name='cb1' type='hidden' value='0' />
     <input name='cb1' type='checkbox' value='1' />


Anyway...back soon.
0
 
LVL 34

Expert Comment

by:Beverley Portlock
ID: 35002478
This still makes no sense to me. Surely you simply run a query to remove everything in array3 from the database and then run another query to insert array4's values?

I cannot see the point of attempting to merge / intersect array3 and array4.

What am I missing?
0
 

Author Comment

by:phpretard
ID: 35002514
Yes, array3 is a dynamic field based on a switch.  

So I can't delete everything...only what is relevant to that page.  

In the picture you will see "Categories" that sends a $_GET['varnumber'] and the switch will select the information from the database to populate array3.
0
 

Author Comment

by:phpretard
ID: 35002517
BTW ... Nice catch
0
 

Author Comment

by:phpretard
ID: 35002534

<?php
switch ($_GET['var'])
{
case 1:
  $title = "About Us";
  $start = "102100000";
  $finish = "102300000";
  break;

case 2:
  $title = "Admissions";
  $start = "103100000";
  $finish = "103700000";
  break;

/*
case 3:
  $title = "ALL Academics";
  $start = "104100000";
  $finish = "104600000";
  break;
*/

case 4:
  $title = "Preschool";
  $start = "104100000";
  $finish = "104102000";
  break;

case 5:
  $title = "Elementary School";
  $start = "104200000";
  $finish = "104210000";
  break;

case 6:
  $title = "Middle School";
  $start = "104300000";
  $finish = "104307000";
  break;

case 7:
  $title = "High School";
  $start = "104400000";
  $finish = "104600000";
  break;

case 8:
  $title = "Boy's Sports";
  $start = "105201000";
  $finish = "105201070";
  break;
  
case 9:
  $title = "Girl's Sports";
  $start = "105202000";
  $finish = "105202070";
  break;

case 10:
  $title = "The Arts";
  $start = "106100000";
  $finish = "106300000";
  break;

case 11:
  $title = "School Life";
  $start = "107100000";
  $finish = "107900000";
  break;

  
default:
  $title = "Select A Category";
  $select_save = "off";
}

?>

and then:

$getpages = "select id, pid, level, name from pages WHERE pid BETWEEN '$start' AND '$finish'";

Open in new window

0
 
LVL 34

Expert Comment

by:Beverley Portlock
ID: 35002678
Well to be honest I would do what I said in my posting above....

foreach( $array3 as $aValue )
     mysql_query("DELETE FROM myTable WHERE number = $aValue");

foreach( $array4 as $aValue )
    mysql_query("INSERT INTO myTable ( number ) VALUES('$aValue') ");

Obviously you could use UPDATE instead of INSERT or DELETE to set or unset a value in the relevant record rather than inserting or deleting it.
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 35002680
This strikes me as a question that maybe should not be asked the way it is asked here.  Can you step back from the detail and please tell us in plain language what you're trying to do?  Is it something like, "I want to know the design pattern for using checkboxes to indicate columns from a data base table?"
0
 
LVL 34

Expert Comment

by:Beverley Portlock
ID: 35002788
Hi Ray - that is why I pointed out the checkbox technique above, that way it would take a simple loop that inserts/updates/deletes based on the value being on or off

foreach( $checkbox as $name => $aCheckbox ) {
     mysql_query("DELETE FROM myTable WHERE number = $name");

     if ( $aCheckbox != 0 )
          mysql_query("INSERT INTO myTable ( number ) VALUES('$name') ");
}


and you're done without any need for array manipulation. It's nearly midnight here Ray so I'll pass this one over to you...

G'night
0
 

Author Comment

by:phpretard
ID: 35002829
I am basically updating the same row for one user (will be multiple eventually).  

This user will have access to certain pages where in this case the pages are numbered.

The numbers are stored (comma separated) in a mysql text field.  

I call the data base for the numbers and explode them into check boxes with the value (of the check box) being the page number.

Then it is determined whether or not the box should be checked or not checked.  This code is working assuming there are comma separated numbers in the aforementioned text field.

Updating the text field is where the problem starts.  

I would like to simply delete and update BUT because each page display a different range of numbers / check boxes this proposes the problem.

I have gotten the code far enough along so that I can actually update the field however storing the information on the page and comparing it on submission is difficult


0
 

Author Comment

by:phpretard
ID: 35002915
This works ...
$array1 = $_POST['page'];
	$array2 = $_POST['page_array'];
	if(empty($_POST['existing'])){$array3 = array();}else{$array3 = explode(",", $_POST['existing']);}
	
	foreach($array1 as $k=>$v) {
		if(in_array($array1[$k], $array2)) unset($array2[$k]);
		if(in_array($array1[$k], $array3)) unset($array3[$k]);
		else $array3[] = $array1[$k];
	
	}

Open in new window

0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 35003297
Nite, nite, Brian.

OK, based on that explanation, please read some of the results of this search:
http://lmgtfy.com?q=Should+I+normalize+my+database

Do not use a CSV string in a TEXT column to store checkboxes.  Use a separate column for each checkbox.  Your life will be instantly simplified!
0
 

Author Comment

by:phpretard
ID: 35005954
Could you please explain how to use separate columns for each check box?
0
 
LVL 34

Expert Comment

by:Beverley Portlock
ID: 35006274
Simply put, you create a table like this

User Page Checkbox_id

FRED  123 1000
FRED  123 1001
FRED  123 1002
MARY  123 1000
MARY  123 1004
FRED  999  1000

etc

You only need to list what checkboxes are allowed for a user on a page. So if Fred is no longer allowed checkbox 1001 on page 123 you simply delete that record.

To find what Fred is allowed on page 123

SELECT checkbox_id FROM myTable WHERE user='FRED' and page=123

0
 

Author Comment

by:phpretard
ID: 35006421
I always find it difficult to explain what I am doing.  I failed to tell you that the "admin" in this case is using the check  boxes to assign numbers to other users. So one person should be able to see all the check boxes and is using them to update permissions for the other users.

With your advise to try and simplify this I put all the check boxes on one page. with the code 2 below.

It made a problem of deciding which page is which as some of them have duplicate page names (not numbers).


$sqlall = "select * from access where pw = '".$_GET['user']."'";
$resultall = mysql_query($sqlall) or die(mysql_error());
while($infoall = mysql_fetch_assoc($resultall)){
echo "<textarea style='width:95%; height:100px;' name='existing'>".$infoall['pid']."</textarea>";
}free($resultall);
		

/** code 2 **/
$getpages = "select id, pid, level, name from pages /*WHERE pid BETWEEN '$start' AND '$finish'*/";
		$getresult = mysql_query($getpages);
			while($pages = mysql_fetch_assoc($getresult)){
			$pagearray = $pages['pid'];
				if(stristr($existing, $pages['pid'])){
					 
					echo "
					<div style='width:20%; float:left;'>
					<input type='checkbox' name='page[]' value='".$pages['pid']."' checked /> ".$pages['name']."
					</div>";
				}else{
					echo "
					<div style='width:20%; float:left;'>
					".$pages['pid']."
					<input type='checkbox' name='page[]' value='".$pages['pid']."' /> ".$pages['name']."
					</div>
					";
				
				}

Open in new window

0
 

Author Comment

by:phpretard
ID: 35006429
Incomplete post above ... stand by
0

Featured Post

Secure Your WordPress Site: 5 Essential Approaches

WordPress is the web's most popular CMS, but its dominance also makes it a target for attackers. Our eBook will show you how to:

Prevent costly exploits of core and plugin vulnerabilities
Repel automated attacks
Lock down your dashboard, secure your code, and protect your users

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article was originally published on Monitis Blog, you can check it here . Today it’s fairly well known that high-performing websites and applications bring in more visitors, higher SEO, and ultimately more sales. By the same token, downtime…
When the s#!t hits the fan, you don’t have time to look up who’s on call, draft emails, call collaborators, or send text messages. An instant chat window is definitely the way to go, especially one like HipChat. HipChat is a true business app. An…
The viewer will learn how to dynamically set the form action using jQuery.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

623 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question