迭代 SimpleXML Objext PHP

发布于 2024-11-03 11:58:55 字数 6106 浏览 0 评论 0原文

这是我的对象与 print_r 的样子(这是由 Amazon Web Services Simple DB 的 PHP SDK 返回的对象)。

[GetAttributesResult] => CFSimpleXML Object
            (
                [Attribute] => Array
                    (
                        [0] => CFSimpleXML Object
                            (
                                [Name] => data_datein
                                [Value] => 2011-04-23
                            )

                        [1] => CFSimpleXML Object
                            (
                                [Name] => data_estatus
                                [Value] => 0
                            )

                        [2] => CFSimpleXML Object
                            (
                                [Name] => data_status
                                [Value] => 1
                            )

                        [3] => CFSimpleXML Object
                            (
                                [Name] => data_title
                                [Value] => Company Info
                            )

                        [4] => CFSimpleXML Object
                            (
                                [Name] => data_tags
                                [Value] => firsttag
                            )

                        [5] => CFSimpleXML Object
                            (
                                [Name] => data_tags
                                [Value] => secondtag
                            )

                        [6] => CFSimpleXML Object
                            (
                                [Name] => data_tags
                                [Value] => thirdtag
                            )

                        [7] => CFSimpleXML Object
                            (
                                [Name] => data_files
                                [Value] => company_info.flv
                            )

                        [8] => CFSimpleXML Object
                            (
                                [Name] => data_id
                                [Value] => 8993
                            )

                    )

            )

我有一个函数可以迭代 GetAttributesResult 对象并创建一个关联数组,可以轻松引用我的字段我的名字之一是 data_tags,它重复了未知次数。我想将 data_tags 作为这些值的简单索引数组返回。这是我的函数,

function attrToArray($select) { 
$results = array(); 
$x = 0; 
foreach($select->body->GetAttributesResult as $result) { 
    foreach ($result as $field) { 
        if (array_key_exists($field,$results[$x])) {
            $results[$x][ (string) $field->Name ][] = (string) $field->Value;
        } else {
            $results[$x][ (string) $field->Name ] = (string) $field->Value; 
        }
    } 
    $x++; 
} 
return $results; 
}

我不知道 它是否有效。如果这是最优雅的解决方案,但我不明白为什么它不起作用。我错误地能够测试 in_array($field-Name,$results[$) x]) 并构建了我重复的 $field->Name 值的数组...但它也将所有其他值转换为单项嵌套数组...所以看起来它返回了 true比我想象的要多。尽管我错误地使用了 -> ,但它并没有返回 true...所以我对那里发生的事情感到非常困惑。这是 print_r 显示返回的内容。

Array ( [0] => Array ( 
[data_datein] => 2011-04-23 
[data_estatus] => 0 
[data_status] => Array ( [0] => 1 ) 
[data_title] => Array ( [0] => Company Info ) 
[data_tags] => Array ( 
    [0] => firsttag
    [1] => secondtag 
    [2] => thirdtag ) 
[data_files] => Array ( [0] => company_info.flv ) 
[data_id] => Array ( [0] => 8993 ) ) ) 

关于如何更好地处理这个问题的任何指针、建议或说明……至少有人能弄清楚如何在没有其他非冗余字段上的嵌套数组的情况下访问上述数组。非常感谢!

这是 $resultprint_r() CFSimpleXML 对象 ( [属性] =>大批 ( [0] => CFSimpleXML 对象 ( [姓名] =>数据日期 [数值] => 2011-04-23 )

        [1] => CFSimpleXML Object
            (
                [Name] => data_estatus
                [Value] => 0
            )

        [2] => CFSimpleXML Object
            (
                [Name] => data_title
                [Value] => 0001 01 Company Name
            )

        [3] => CFSimpleXML Object
            (
                [Name] => data_status
                [Value] => 1
            )

        [4] => CFSimpleXML Object
            (
                [Name] => data_tags
                [Value] => good stuff
            )

        [5] => CFSimpleXML Object
            (
                [Name] => data_tags
                [Value] => save tags
            )

        [6] => CFSimpleXML Object
            (
                [Name] => data_tags
                [Value] => tagger works
            )

        [7] => CFSimpleXML Object
            (
                [Name] => data_files
                [Value] => 0001_01_company_name.flv
            )

        [8] => CFSimpleXML Object
            (
                [Name] => data_id
                [Value] => yFKwIxjIhH
            )

    )

)

,这里是 $fieldprint_r() (迭代并由


标签分隔。)

  CFSimpleXML Object
  (
      [Name] => data_datein
      [Value] => 2011-04-23
  )
  <hr>CFSimpleXML Object
  (
      [Name] => data_estatus
      [Value] => 0
  )
  <hr>CFSimpleXML Object
  (
      [Name] => data_title
      [Value] => 0001 01 Company Name
  )
  <hr>CFSimpleXML Object
  (
      [Name] => data_status
      [Value] => 1
  )
  <hr>CFSimpleXML Object
  (
      [Name] => data_tags
      [Value] => good stuff
  )
  <hr>CFSimpleXML Object
  (
      [Name] => data_tags
      [Value] => save tags
  )
  <hr>CFSimpleXML Object
  (
      [Name] => data_tags
      [Value] => tagger works
  )
  <hr>CFSimpleXML Object
  (
      [Name] => data_files
      [Value] => 0001_01_company_name.flv
  )
  <hr>CFSimpleXML Object
  (
      [Name] => data_id
      [Value] => yFKwIxjIhH
  )

Here is what my object looks like with print_r (this is an object returned by the PHP SDK for the Amazon Web Services Simple DB.

[GetAttributesResult] => CFSimpleXML Object
            (
                [Attribute] => Array
                    (
                        [0] => CFSimpleXML Object
                            (
                                [Name] => data_datein
                                [Value] => 2011-04-23
                            )

                        [1] => CFSimpleXML Object
                            (
                                [Name] => data_estatus
                                [Value] => 0
                            )

                        [2] => CFSimpleXML Object
                            (
                                [Name] => data_status
                                [Value] => 1
                            )

                        [3] => CFSimpleXML Object
                            (
                                [Name] => data_title
                                [Value] => Company Info
                            )

                        [4] => CFSimpleXML Object
                            (
                                [Name] => data_tags
                                [Value] => firsttag
                            )

                        [5] => CFSimpleXML Object
                            (
                                [Name] => data_tags
                                [Value] => secondtag
                            )

                        [6] => CFSimpleXML Object
                            (
                                [Name] => data_tags
                                [Value] => thirdtag
                            )

                        [7] => CFSimpleXML Object
                            (
                                [Name] => data_files
                                [Value] => company_info.flv
                            )

                        [8] => CFSimpleXML Object
                            (
                                [Name] => data_id
                                [Value] => 8993
                            )

                    )

            )

I have a function that iterates over the GetAttributesResult Object and creates an associative array that makes it easy to reference my fields by their names. One of my Names is data_tags, which is repeated an unknown number of times. I would like to return data_tags as a simple indexed array of those values. Here's my function, which doesn't work.

function attrToArray($select) { 
$results = array(); 
$x = 0; 
foreach($select->body->GetAttributesResult as $result) { 
    foreach ($result as $field) { 
        if (array_key_exists($field,$results[$x])) {
            $results[$x][ (string) $field->Name ][] = (string) $field->Value;
        } else {
            $results[$x][ (string) $field->Name ] = (string) $field->Value; 
        }
    } 
    $x++; 
} 
return $results; 
}

I don't know if this is the most elegant solution, but I don't see why it wouldn't work. array_key_exists doesn't return true. By mistake I was able to test as in_array($field-Name,$results[$x]) and that built the array of my repeated $field->Name values... but it also converted all of the other values into single item nested array... so it would seem that it returned true more than I thought it would have. Although the hyphen in there was by mistake I meant to use -> which doesn't return true... so I'm very confused by what is going on there. Here's the print_r to show what came back.

Array ( [0] => Array ( 
[data_datein] => 2011-04-23 
[data_estatus] => 0 
[data_status] => Array ( [0] => 1 ) 
[data_title] => Array ( [0] => Company Info ) 
[data_tags] => Array ( 
    [0] => firsttag
    [1] => secondtag 
    [2] => thirdtag ) 
[data_files] => Array ( [0] => company_info.flv ) 
[data_id] => Array ( [0] => 8993 ) ) ) 

Any pointers, suggestions or instruction on how I might handle this better... and at very least if someone can figure out how I can get to the above array without the nested arrays on the other non-redundant fields. Very much appreciated!

Here is the print_r() of $result
CFSimpleXML Object
(
[Attribute] => Array
(
[0] => CFSimpleXML Object
(
[Name] => data_datein
[Value] => 2011-04-23
)

        [1] => CFSimpleXML Object
            (
                [Name] => data_estatus
                [Value] => 0
            )

        [2] => CFSimpleXML Object
            (
                [Name] => data_title
                [Value] => 0001 01 Company Name
            )

        [3] => CFSimpleXML Object
            (
                [Name] => data_status
                [Value] => 1
            )

        [4] => CFSimpleXML Object
            (
                [Name] => data_tags
                [Value] => good stuff
            )

        [5] => CFSimpleXML Object
            (
                [Name] => data_tags
                [Value] => save tags
            )

        [6] => CFSimpleXML Object
            (
                [Name] => data_tags
                [Value] => tagger works
            )

        [7] => CFSimpleXML Object
            (
                [Name] => data_files
                [Value] => 0001_01_company_name.flv
            )

        [8] => CFSimpleXML Object
            (
                [Name] => data_id
                [Value] => yFKwIxjIhH
            )

    )

)

and here is a print_r() of $field (iterated and separated by <hr> tags.)

  CFSimpleXML Object
  (
      [Name] => data_datein
      [Value] => 2011-04-23
  )
  <hr>CFSimpleXML Object
  (
      [Name] => data_estatus
      [Value] => 0
  )
  <hr>CFSimpleXML Object
  (
      [Name] => data_title
      [Value] => 0001 01 Company Name
  )
  <hr>CFSimpleXML Object
  (
      [Name] => data_status
      [Value] => 1
  )
  <hr>CFSimpleXML Object
  (
      [Name] => data_tags
      [Value] => good stuff
  )
  <hr>CFSimpleXML Object
  (
      [Name] => data_tags
      [Value] => save tags
  )
  <hr>CFSimpleXML Object
  (
      [Name] => data_tags
      [Value] => tagger works
  )
  <hr>CFSimpleXML Object
  (
      [Name] => data_files
      [Value] => 0001_01_company_name.flv
  )
  <hr>CFSimpleXML Object
  (
      [Name] => data_id
      [Value] => yFKwIxjIhH
  )

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

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

发布评论

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

评论(5

时光倒影 2024-11-10 11:58:55

在 AWS PHP 开发工具包中,您可以使用 to_json()、< a href="http://docs.amazonwebservices.com/AWSSDKforPHP/latest/#m=CFSimpleXML/to_stdClass" rel="noreferrer">to_stdClass() 甚至 to_array() 从 CFSimpleXML 对象获取其他数据类型。对于 SimpleXML 对象来说,类型转换也是关键!

PHP 有一个名为 ArrayObject 的对象,它或多或少是数组的 OOP 版本。当您调用 CFSimpleXML->to_array() 时,您将返回一个 CFArray 对象,该对象包装了具有额外功能的本机 ArrayObject 对象。

$array = $response->body->GetAttributesResult->to_array();
list($name, $value) = $array['Attribute']->first()->map(function($node, $i) {
    return (string) $node;
});

http://docs.amazonwebservices.com/AWSSDKforPHP/latest/#i=CFSimpleXML
http://docs.amazonwebservices.com/AWSSDKforPHP/latest/#i=CFArray

In the AWS PHP SDK, you can use to_json(), to_stdClass() and even to_array() to get back other data types from a CFSimpleXML object. Also with SimpleXML objects, typecasting is key!

PHP has an object called ArrayObject which is more-or-less an OOP version of an array. When you call CFSimpleXML->to_array(), you get back a CFArray object, which wraps the native ArrayObject object with extra functionality.

$array = $response->body->GetAttributesResult->to_array();
list($name, $value) = $array['Attribute']->first()->map(function($node, $i) {
    return (string) $node;
});

http://docs.amazonwebservices.com/AWSSDKforPHP/latest/#i=CFSimpleXML
http://docs.amazonwebservices.com/AWSSDKforPHP/latest/#i=CFArray

菩提树下叶撕阳。 2024-11-10 11:58:55

在此处输入代码您的意思是这样吗:

$data_tags = array();
foreach ( $select->body->GetAttributesResult AS $attr ) {
  if ( $attr->Name == 'data_tags' ) {
    $data_tags[] = $attr->Value;
  }
}

否则,我不知道您想要什么 =)

编辑
您确定 GetAttributesResult 正确吗?你不是说 http://www.php.net/manual/en/ simplexmlelement.attributes.php

enter code hereDo you mean something like this:

$data_tags = array();
foreach ( $select->body->GetAttributesResult AS $attr ) {
  if ( $attr->Name == 'data_tags' ) {
    $data_tags[] = $attr->Value;
  }
}

Otherwise, I don't know what you want =)

edit
Are you sure GetAttributesResult is right? Don't you mean http://www.php.net/manual/en/simplexmlelement.attributes.php?

地狱即天堂 2024-11-10 11:58:55

我会建议类似的事情。

更新:

function getAttributesIntoArray( $select )
{
    $results = array();
    $x       = 0;

    foreach ( $select->body->GetAttributesResult as $result )
    {
        foreach ( $result as $field )
        {
            if ( ! isset( $results[ $x ] ) )
            {
                $results[ $x ] = array();
            }

            // Assuming, that if the $field->Value is array, then it probably have only one element
            if ( $field )
            {
                // or if ( isset( $results[ $x ][ (string) $field->Name ] ) ) instead of array_key_exists
                if ( array_key_exists( (string) $field->Name, $results[ $x ] ) )
                {
                    $results[ $x ][ (string) $field->Name ][] = ( is_array( $field->Value ) ) ? $field->Value[0] : $field->Value;
                }
                else
                {
                    $results[ $x ][ (string) $field->Name ] = ( is_array( $field->Value ) ) ? $field->Value[0] : $field->Value;
                }
            }
        }

        $x++; 
    }

    return $results;
}

I would suggest something like that.

UPDATED:

function getAttributesIntoArray( $select )
{
    $results = array();
    $x       = 0;

    foreach ( $select->body->GetAttributesResult as $result )
    {
        foreach ( $result as $field )
        {
            if ( ! isset( $results[ $x ] ) )
            {
                $results[ $x ] = array();
            }

            // Assuming, that if the $field->Value is array, then it probably have only one element
            if ( $field )
            {
                // or if ( isset( $results[ $x ][ (string) $field->Name ] ) ) instead of array_key_exists
                if ( array_key_exists( (string) $field->Name, $results[ $x ] ) )
                {
                    $results[ $x ][ (string) $field->Name ][] = ( is_array( $field->Value ) ) ? $field->Value[0] : $field->Value;
                }
                else
                {
                    $results[ $x ][ (string) $field->Name ] = ( is_array( $field->Value ) ) ? $field->Value[0] : $field->Value;
                }
            }
        }

        $x++; 
    }

    return $results;
}
倥絔 2024-11-10 11:58:55

我能够让这个工作。希望这有帮助。

protected function CFResponseToArray($response)
    {
        try {
            if ($response->isOK()) {
            $responseObj = $response->body->to_array()->getArrayCopy();
            //log_message('info', print_r($responseObj, true));
            $result = array();
            if (isset($responseObj['SelectResult']['Item'])) {
                if (is_array($responseObj['SelectResult']['Item'])) {
                    if (isset($responseObj['SelectResult']['Item']['Name'])) {
                        $itemObj = array();
                        //log_message('info', print_r($responseObj['SelectResult'], true));
                        $resultItem = $responseObj['SelectResult']['Item'];
                        $itemObj['Id'] = $resultItem['Name'];
                        $attributes = $resultItem['Attribute'];
                        for ($i = 0; $i < count($attributes); $i++) {
                            $itemObj[$attributes[$i]['Name']] = $attributes[$i]['Value'];
                        }
                        $result[] = $itemObj;
                    } else {
                        //log_message('info', print_r($responseObj['SelectResult'], true));
                        foreach ($responseObj['SelectResult']['Item'] as $resultItem) {

                            $itemObj = array();
                            $itemObj['Id'] = $resultItem['Name'];
                            $attributes = $resultItem['Attribute'];
                            for ($i = 0; $i < count($attributes); $i++) {
                                $itemObj[$attributes[$i]['Name']] = is_array($attributes[$i]['Value']) ? "" : $attributes[$i]['Value'];
                            }
                            $result[] = $itemObj;
                        }
                        if (isset($responseObj['SelectResult']['NextToken'])) {
                            $this->nextToken = $responseObj['SelectResult']['NextToken'];
                        } else {
                            $this->nextToken = '';
                        }
                    }
                }
            }
            return $result;
        }
        } catch (exception $ex) {
            log_message('error', $ex->getMessage());
        }

    }

I was able to get this one to work. Hope this helps.

protected function CFResponseToArray($response)
    {
        try {
            if ($response->isOK()) {
            $responseObj = $response->body->to_array()->getArrayCopy();
            //log_message('info', print_r($responseObj, true));
            $result = array();
            if (isset($responseObj['SelectResult']['Item'])) {
                if (is_array($responseObj['SelectResult']['Item'])) {
                    if (isset($responseObj['SelectResult']['Item']['Name'])) {
                        $itemObj = array();
                        //log_message('info', print_r($responseObj['SelectResult'], true));
                        $resultItem = $responseObj['SelectResult']['Item'];
                        $itemObj['Id'] = $resultItem['Name'];
                        $attributes = $resultItem['Attribute'];
                        for ($i = 0; $i < count($attributes); $i++) {
                            $itemObj[$attributes[$i]['Name']] = $attributes[$i]['Value'];
                        }
                        $result[] = $itemObj;
                    } else {
                        //log_message('info', print_r($responseObj['SelectResult'], true));
                        foreach ($responseObj['SelectResult']['Item'] as $resultItem) {

                            $itemObj = array();
                            $itemObj['Id'] = $resultItem['Name'];
                            $attributes = $resultItem['Attribute'];
                            for ($i = 0; $i < count($attributes); $i++) {
                                $itemObj[$attributes[$i]['Name']] = is_array($attributes[$i]['Value']) ? "" : $attributes[$i]['Value'];
                            }
                            $result[] = $itemObj;
                        }
                        if (isset($responseObj['SelectResult']['NextToken'])) {
                            $this->nextToken = $responseObj['SelectResult']['NextToken'];
                        } else {
                            $this->nextToken = '';
                        }
                    }
                }
            }
            return $result;
        }
        } catch (exception $ex) {
            log_message('error', $ex->getMessage());
        }

    }
任谁 2024-11-10 11:58:55
function attrToArray($select) { 
$results = array(); 
$x = 0;
foreach ( $select->body->GetAttributesResult as $result ) {
    foreach ( $result as $field ) {
        $check = (string) $field->Name;
        if (isset($field) && array_key_exists($check, $results[$x] ) ) {
            if ( ! is_array( $results[ $x ][$check] ) ) {
                $val = (string) $results[ $x ][$check];
                $results[ $x ][ $check ] = array();
                $results[ $x ][ $check ][] = $val;
            }
        $results[ $x ][ $check ][] = (string) $field->Value;
        } else {
            $results[ $x ][ $check ] = (string) $field->Value;
        }
    }
    $x++; 
}
return $results; 
}
function attrToArray($select) { 
$results = array(); 
$x = 0;
foreach ( $select->body->GetAttributesResult as $result ) {
    foreach ( $result as $field ) {
        $check = (string) $field->Name;
        if (isset($field) && array_key_exists($check, $results[$x] ) ) {
            if ( ! is_array( $results[ $x ][$check] ) ) {
                $val = (string) $results[ $x ][$check];
                $results[ $x ][ $check ] = array();
                $results[ $x ][ $check ][] = $val;
            }
        $results[ $x ][ $check ][] = (string) $field->Value;
        } else {
            $results[ $x ][ $check ] = (string) $field->Value;
        }
    }
    $x++; 
}
return $results; 
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文