在php中将属性值设置为其数组键

发布于 2024-10-01 08:48:27 字数 698 浏览 4 评论 0原文

(删除 XML 节点后)以下内容获取列表: 'id' 属性值:

$objXML = new SimpleXMLElement(XML_FILE_NAME, null, true);
$picture = $objXML->xpath('picture');
$arrayCurrent = array();
foreach($picture as $value) {
    $arrayCurrent[] = (string)$value['id'];
}
sort($arrayCurrent); // required as XML nodes not in numerical 'id' order
print_r($arrayCurrent);

返回以下内容:

Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 5 [5] => 6 [6] => 7 [7] => 8 )

我想将每个 id 设置为其当前键的值,如下所示:

Array ( [0 ] => 1 [2] => 3 [4] => 5 [6] => => 7)

我已经搞乱了一段时间,但我想知道是否有一种简单的方法可以实现这一点?

(after deleting an XML node) the following gets a list of <picture> 'id' attribute values:

$objXML = new SimpleXMLElement(XML_FILE_NAME, null, true);
$picture = $objXML->xpath('picture');
$arrayCurrent = array();
foreach($picture as $value) {
    $arrayCurrent[] = (string)$value['id'];
}
sort($arrayCurrent); // required as XML nodes not in numerical 'id' order
print_r($arrayCurrent);

Which returns the following:

Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 5 [5] => 6 [6] => 7 [7] => 8 )

I want to set each id to the value of its current key like so:

Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 [6] => 6 [7] => 7 )

I've been messing about with this for a while but I wondered if there is a simple way to achieve this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

烟火散人牵绊 2024-10-08 08:48:27

如果您显式分配索引键并使用 asort,我认为你会得到你想要的。

...
foreach($picture as $value) {
    $arrayCurrent[$value['id']] = (string)$value['id'];
}
asort($arrayCurrent); // required as XML nodes not in numerical 'id' order
...

第二次尝试..仍然不确定我理解你,但是嘿:)而不是 foreach 循环:

for($i = 0; $i < sizeof($picture); $i++)
{
  $picture[$i]['id'] = $i;
  $arrayCurrent[$i] = $i; // Not sure why you'd still want this, in this case.
}

If you explicitly assign index keys and use asort, I think you'll get what you want.

...
foreach($picture as $value) {
    $arrayCurrent[$value['id']] = (string)$value['id'];
}
asort($arrayCurrent); // required as XML nodes not in numerical 'id' order
...

Second try.. still not sure I understand you, but hey :) Instead of the foreach loop:

for($i = 0; $i < sizeof($picture); $i++)
{
  $picture[$i]['id'] = $i;
  $arrayCurrent[$i] = $i; // Not sure why you'd still want this, in this case.
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文