How do you convert keys from major to minor?

How can I convert particular array keys to numeric?

  • The following code converts an array to a XML string and vice versa. In the process of converting the array to XML, it converts numeric keys to have the prefix of double underscores since XML does not allow numbers to be a tag. The problem is that when converting back to an array, it does not revert the prefixed numeric keys. Is it possible to remove them and to have pure numeric keys? <?php $array = array( array( 'a' => 'aaa', 'b' => array( array( 'a' => 'aaaa', ), array( 'a' => 'aaaa', 'b' => 'bbbb', ), ) ), array( 'a' => 'abc', 'b' => array( array( 'c' => 'cccc', ), array( 'b' => 'bbbb', 'd' => array( 'a', 'b', 'c', 'd' ) ) ) ) ); Array2XML( $array, $oSimpleXML ); XML2Array( $oSimpleXML->asXML(), $xml_array ); echo '<pre>' . print_r( $array, true ) . '</pre>'; echo '<pre>' . print_r( $xml_array, true ) . '</pre>'; function Array2XML( $arr, &$oSimpleXML ) { if ( !is_object( $oSimpleXML ) ) $oSimpleXML = new SimpleXMLElement("<?xml version=\"1.0\"?><root></root>"); foreach( $arr as $key => $value ) { if ( is_array( $value ) ) { $node = $oSimpleXML->addChild( is_numeric( $key ) ? "__$key" : "$key" ); Array2XML( $value, $node ); continue; } $oSimpleXML->addChild( is_numeric( $key ) ? "__$key" : "$key", "$value" ); } } function XML2Array( $xml, &$array ) { $array = json_decode( json_encode( ( array ) simplexml_load_string( $xml ) ), 1 ); }

  • Answer:

    Hi there, http://stackoverflow.com/questions/3808602/recursively-replace-keys-in-an-array Just tested it, looks like it'll work for you! A

Adam Marshall at Quora Visit the source

Was this solution helpful to you?

Other answers

For the record, one can simply create numerical values for non-numeric keys by simply setting up a variable. <?php $a=[ [ 'name'=>'name test 0', 'url'=>'url test 0', 'img'=>'img test 0' ], [ 'name'=>'name test 1', 'url'=>'url test 1', 'img'=>'img test 1' ] ]; foreach ($a as $gk => $gv) { $ic=0; foreach ($gv as $ik => $iv) { echo '<p class="'.$ik.'" id="id_g-'.$gk.'_i-'.$ic.'">'.$iv.'</p> '; ++$ic; } } ?> That will output: <p class="name" id="id_g-0_i-0">name test 0</p> <p class="url" id="id_g-0_i-1">url test 0</p> <p class="img" id="id_g-0_i-2">img test 0</p> <p class="name" id="id_g-1_i-0">name test 1</p> <p class="url" id="id_g-1_i-1">url test 1</p> <p class="img" id="id_g-1_i-2">img test 1</p>

Elliott Hotchkiss

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.