使用php从多维数组中提取值

时间:2011-02-19 20:29:12

标签: php multidimensional-array

我有一个像这样的多维数组,已发布到php脚本

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

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

在php中,我首先需要从每个数组项中获取onlineid,以便可以在select语句(mysql)中使用它来查看用户是否存在。

然后在第二次或同时我需要循环遍历数组中的每个onlineid并提取每个键的值(如示例中的注释和图像),以便它们可用于更新mysql数据库。 / p>

最好的方法是什么?

1 个答案:

答案 0 :(得分:0)

$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...
  }
}

或者我错过了这一点?