简体   繁体   中英

Extract values from a multidimensional array using php

I have a multidimensional array like this which has been posted to a php script

Array
(
     [users] => Array
           (
              [0] => Array
                    (
                         [onlineid] => person1
                         [comment] => comment1
                         [img] => image1
                    )

              [1] => Array
                    (
                         [onlineid] => person2
                         [comment] => comment2
                         [img] => image2
                    )
           )
)

In php, i firstly need to obtain only the onlineid from each array item so that it can be used in a select statement (mysql) to see if the user exists.

Then secondly or at the same time i need to loop through each onlineid in the array and extract the values for each key (like the comment and image in the example) so that they can be used to update a mysql database.

What is the best way to approach this?

$myAry = array(...); // the one you have listed in your question

// goes through each user entry in the array, and makes it an individual
// variable we can reference (in this case '$user')
foreach ($myAry['users'] as $user)
{
  // create the update query using the values from the element
  $sql = "UPDATE mytable
          SET    comment={$user[comment]},
                 img={$user[img]}
          WHERE  onlineid={$user[onlineid]}";
  // pass it off to mysql (or whatever connection you want)
  if (($result = mysql_query($sql)) !== false)
  {
    // all went well, ...additional code here...
  }
}

Or am I missing the point on this one?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM