Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I guess the people suggesting to use <a href="http://code.google.com/p/simpledom/" rel="nofollow noreferrer">SimpleDOM</a> would be me. :)</p> <p>I've written SimpleDOM::sort() exactly for that situation, because in order to sort SimpleXMLElements by an arbitration expression (or arbitrary expressions) you need to use <a href="http://docs.php.net/manual/en/function.array-multisort.php" rel="nofollow noreferrer"><code>array_multisort()</code></a> which is boring and won't teach you anything useful.</p> <p>Here's the short version of how it works: first you create a proxy array of key=>value pairs corresponding to each SimpleXMLElement and the value with which they'll be sorted. In your example, if you want to sort them by <code>&lt;age/&gt;</code>, the array would be <code>array(21, 56)</code>. Then you call <code>array_multisort()</code> with the "proxy array" as first argument, followed by any number of <a href="http://docs.php.net/manual/en/array.constants.php" rel="nofollow noreferrer">sorting modifiers</a> such as SORT_DESC or SORT_NUMERIC then finally the array you want to sort, which will be passed by reference.</p> <p>You will end up with something like that:</p> <pre><code>$nodes = array( new SimpleXMLElement('&lt;person&gt;&lt;name&gt;Andrew&lt;/name&gt;&lt;age&gt;21&lt;/age&gt;&lt;/person&gt;'), new SimpleXMLElement('&lt;person&gt;&lt;name&gt;Beth&lt;/name&gt;&lt;age&gt;56&lt;/age&gt;&lt;/person&gt;') ); function xsort(&amp;$nodes, $child_name, $order = SORT_ASC) { $sort_proxy = array(); foreach ($nodes as $k =&gt; $node) { $sort_proxy[$k] = (string) $node-&gt;$child_name; } array_multisort($sort_proxy, $order, $nodes); } xsort($nodes, 'name', SORT_ASC); print_r($nodes); xsort($nodes, 'age', SORT_DESC); print_r($nodes); </code></pre> <p>But really, instead of burdening yourself with more code you'll have to maintain and possibly ending up rewriting <code>array_multisort()</code> in userspace, you should leverage existing solutions. There's nothing interesting in such a sorting algorithm/routine, your time would be better spent on something that doesn't already exist.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload