Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/250.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP foreach循环元素索引_Php_Foreach_Nodelist - Fatal编程技术网

PHP foreach循环元素索引

PHP foreach循环元素索引,php,foreach,nodelist,Php,Foreach,Nodelist,我有一个XPath查询,可以获取电影的类型 $genreXpath = $xml_data->xpath("//category"); 我从$genreXpath获得如下属性 $genreName=array(); $genresID=array(); $i=0; foreach($genreXpath as $node) { $genre = $node->attributes(); $genreName[$i] = $node["name"]; $ge

我有一个XPath查询,可以获取电影的类型

$genreXpath = $xml_data->xpath("//category");
我从$genreXpath获得如下属性

$genreName=array();
$genresID=array();
$i=0;

foreach($genreXpath as $node) {
    $genre = $node->attributes();
    $genreName[$i] = $node["name"];
    $genresID[$i] = $node["id"];    

        $i++;
}
我将把这些值写入一个Db,从而得到两个不同的数组。 这段代码可以工作,但我知道必须有更好的方法来实现这一点,可以使用2D数组,而不是使用$I计数器或其他我没有想到的更明显的东西……有什么指针吗

foreach($genreXpath as $i=>$node) {  //note $i is your index of the current $node
    $genre = $node->attributes();
    $genreName[$i] = $node["name"];
    $genresID[$i] = $node["id"];    
}

它会自动递增,您不需要在上面声明它。

使用foreach$genreXpath作为$key=>$node{

如果您要查看多维数据,您可以执行以下操作:

$genres = array();
foreach($genreXpath as $node) {
    $genre = $node->attributes();
    $genres[] = array($node["name"], $node["id"]);
}

你可能想删除$i++hah,在你的评论出现之前大约10秒。谢谢。非常感谢,我是用另一种方式来做的$node->$i,我会到达那里的。当我做SQL insert语句时,这是如何工作的……有点离题,但当我们这样做时:@user644347-我会使用内爆。加入值,然后加入行。