Click to See Complete Forum and Search --> : [RESOLVED] 1-based array?


bustya
10-22-2008, 11:59 PM
I'm trying to change this array to 1-based with no luck, any help appreciated.



<?php
/* on form submission */
if(isset($_POST['do_submit']))
{
/* split the value of the sortation */
$ids = explode('|',$_POST['disorder']);

/* run the update query for each id */
foreach($ids as $index=>$id)
{
if($id != '')
{
$q = "UPDATE images SET disorder = '$index' WHERE uploadee = '$user' AND id = '$id'";
$result = $database->query($q);
}
}

/* now what? */
if($_POST['byajax']) { die(); } else { $message = 'Sortation has been saved.'; }
}
?>

<?php
$q = "SELECT id, filename FROM images WHERE uploadee = '$user' ORDER BY disorder ASC";
$result = $database->query($q);
if(mysql_num_rows($result)) {
?>
<p>Drag and drop the elements below. The database gets updated on every drop.</p>

<div id="message-box"><?php echo $message; ?> Waiting for sortation submission...</div>

<form id="dd-form" action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="post">
<p><input type="checkbox" value="1" name="auto_submit" id="auto_submit" <?php if($_POST['auto_submit']) { echo 'checked="checked"'; } ?> /> <label for="auto_submit">Automatically submit on drop event</label></p>

<ul id="sortable-list">
<?php
$disorder = array();
while($item = mysql_fetch_assoc($result))
{
echo '<li class="sortme" alt="',$item['id'],'">',$item['filename'],'</li>';
$disorder[] = $item['id'];
}
?>
</ul>
<br />
<input type="hidden" name="disorder" id="disorder" value="<?php echo implode($disorder,'|'); ?>" />
<input type="submit" name="do_submit" id="do_submit" value="Submit Sortation" class="button" />
</form>
<?php } else { ?>

bustya
10-23-2008, 01:02 AM
In other words... I need the array to begin with 1 instead of 0.

NogDog
10-23-2008, 01:41 AM
With the caveat that it probably should not be necessary, one kludge would be to initialize the array with a dummy element at index 0, then after you are done populating it, simply do an unset($array_name[0]). But like I said, normally this should really not be an issue.

bustya
10-23-2008, 01:57 AM
The default of this column begins with 1 but once sorted through the array it becomes 0... this was throwing a major monkey wrench in my design's logic because there's yet another column in another table that limits the amount of rows a given user can insert. But I just figured out the fix for this and it's rather simple:


$newindex = $index +1;
$q = "UPDATE images SET disorder = '$newindex' WHERE uploadee = '$user' AND id = '$id'";
$result = $database->query($q);



But thanks for your response. I'm marking this resolved.

NogDog
10-23-2008, 03:42 AM
In case it might help in future situations, note that asort (http://www.php.net/asort)() maintains the array key/value association.