Jump to content


Photo

Help with the dreaded multidimensional associative array extract


  • Please log in to reply
2 replies to this topic

#1 tcicatelli

tcicatelli
  • New Members
  • Pip
  • Newbie
  • 1 posts

Posted 01 October 2006 - 05:58 PM

Hi-

I'm writing an application that extracts a ton of information from a client and pushes it to a server in an associative array.  What I am looking to do, is be able to create a foreach loop to take the "laundry array" and extract "shirt", "red", "clean" and "pants", "blue", "dirty" as separate variables so I can insert them into a mysql table.  I want to ignore all the client_info data because I take care of that separately, since I know there's always just one client, but  I'm never sure of how many "laundry" items will be forwarded.  Here's a sample data dump:

array(2) {
  ["client_info"]=>
  array(2) {
    ["client_fname"]=>
    string(20) "John"
    ["client_lname"]=>
    string(20) "Smith"
  }
  ["laundry"]=>
  array(2) {
    ["Shirt"]=>
    array(2) {
      ["color"]=>
      string(15) "red"
      ["status"]=>
      string(5) "clean"
    }
    ["Pants"]=>
    array(2) {
      ["color"]=>
      string(15) "blue"
      ["status"]=>
      string(5) "dirty"
    }

  }
}

I'm hoping to be able to write:

mysql_query("INSERT INTO Inventory (Item, Color, Status ) VALUES($item, $color, $status)")


I hope I've explained this well enough.

Thanks,
-Tom

#2 Barand

Barand
  • Moderators
  • Sen . ( ile || sei )
  • 18,021 posts

Posted 01 October 2006 - 06:25 PM

<?php
foreach ($data['laundry'] as $item => $itemdata) {
        $color = $itemdata['color'];
        $status = $itemdata['status'];
        
        echo $item, ' ', $color, ' ', $status, '<br>';
}
?>

If you are still using mysql_ functions, STOP! Use mysqli_ or PDO. The longer you leave it the more you will have to rewrite.

Donations gratefully received






moon.png

|baaGrid| easy data tables - and more
|baaChart| easy line, column and pie charts

#3 sasa

sasa
  • Staff Alumni
  • Advanced Member
  • 2,804 posts
  • LocationHrvatska

Posted 01 October 2006 - 06:28 PM

TRY
<?php
$a = array(
"client_info" => 
	array("client_fname" => "John", "client_lname" => "Smith"),
"laundry" =>
	array("Shirt" =>
		array("color" => "red", "status" => "clean"),
    "Pants" =>
    	array("color" => "blue", "status" => "dirty")
    )
);
foreach ($a['laundry'] as $k => $v) {
	$b[] = "('$k', '{$v[color]}', '{$v[status]}')";
}
$b = implode(', ', $b);
$sql = "INSERT INTO Inventory (Item, Color, Status ) VALUES {$b}";
echo $sql;
?>





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users