Search code examples
phparraysstringforeachinclusion

Php Changing a consecutive array to a inclusive array


I am working on a latin website that holds some information in a string this way:

nominative:0:us,a,um;genitive:0:i;dative,ablative:1:is

I would like to turn this information into an array like this

array(
    'nominative'=>array(
        0=>array('us','a','um')
    ),
    'genitive'=>array(
        0=>'i'
    )
    'dative'=>array(
        1=>'is'
    )
    'ablative'=>array(
        1=>'is'
    )
)

My current code looks like this

//turn into array for each specification
$specs=explode(';',$specificities);
foreach($specs as $spec):
    //turn each specification into a consecutive array
    $parts=explode(':',$spec);
    //turn multiple value into array
    foreach($parts as &$value)
        if(strpos($value,',')!==false)
            $value=explode(',',$value);
    //imbricate into one other
    while(count($parts)!==1):
        $val=array_pop($parts);
        $key=array_pop($parts);
        if(is_array($key)):
            foreach($key as $k)
                $parts[$k]=$val;
        else:
            $parts[$key]=$val;
        endif;
    endwhile;
endforeach;

I'm stuck. Help.


Edit: Thanks for the quick responses everybody! The response I preferred was from CaCtus. I modified it to add flexibility but it was the most useful.

For those interested, here is the new code:

$parts=explode(';','nominative:0:er,ra,rum;genitive:0:i;dative,ablative:1:is;root:r;');
if(!empty($parts)&&!empty($parts[0])):
    foreach($parts as $part):
        $subpart=explode(':',$part);
        $keys=explode(',',$subpart[0]);
        foreach($keys as $key):
            @$vals=(strpos($subpart[2],',')!==false)
                ?explode(',',$subpart[2])
                :$subpart[2];
            $final=(is_null($vals))
                ?$subpart[1]
                :array($subpart[1]=>$vals);
        endforeach;          
    endforeach;
endif;

Solution

  • $string = 'nominative:0:us,a,um;genitive:0:i;dative,ablative:1:is';
    $finalArray = array();
    
    // Separate each specification
    $parts = explode(';', $string);
    foreach($parts as $part) {
        // Get values : specification name, index and value
        $subpart = explode(':', $part);
    
        // Get different specification names
        $keys = explode(',', $subpart[0]);
    
        foreach($keys as $key) {            
            if (preg_match('#,#', $subpart[2])) {
            // Several values
                $finalValues =  explode(',', $subpart[2]);
            } else {
            // Only one value
                $finalValues = $subpart[2];
            }
    
            $finalArray[$key] = array(
                $subpart[1] => $finalValues
            );
        }
    }