How to process a large post array in PHP where item names are all different and not known in advance

Posted by Salnajjar on Stack Overflow See other posts from Stack Overflow or by Salnajjar
Published on 2010-03-28T15:21:29Z Indexed on 2010/03/28 15:33 UTC
Read the original article Hit count: 152

Filed under:
|

I have a PHP page that queries a DB to populate a form for the user to modify the data and submit.
The query returns a number of rows which contain 3 items:

  1. ImageID
  2. ImageName
  3. ImageDescription

The PHP page titles each box in the form with a generic name and appends the ImageID to it. Ie:

  • ImageID_03
  • ImageName_34
  • ImageDescription_22

As it's unknown which images are going to have been retrieved from the DB then I can't know in advance what the name of the form entries will be. The form deals with a large number of entries at the same time.

My backend PHP form processor that gets the data just sees it as one big array:

[imageid_2] => 2
[imagename_2] => _MG_0214
[imageid_10] => 10
[imagename_10] => _MG_0419
[imageid_39] => 39
[imagename_39] => _MG_0420
[imageid_22] => 22
[imagename_22] => Curly Fern
[imagedescription_2] => Wibble
[imagedescription_10] => Wobble
[imagedescription_39] => Fred
[imagedescription_22] => Sally

I've tried to do an array walk on it to split it into 3 arrays which set places but am stuck:

// define empty arrays
$imageidarray = array();
$imagenamearray = array();
$imagedescriptionarray = array();

// our function to call when we walk through the posted items array
function assignvars($entry, $key)
{
 if (preg_match("/imageid/i", $key)) { 
  array_push($imageidarray, $entry);
 } elseif (preg_match("/imagename/i", $key)) {
//     echo " ImageName: $entry";
 } elseif (preg_match("/imagedescription/i", $key)) {
//     echo " ImageDescription: $entry";
 }
}

array_walk($_POST, 'assignvars');

This fails with the error:
array_push(): First argument should be an array in...

Am I approaching this wrong?

© Stack Overflow or respective owner

Related posts about php

Related posts about arrays