Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting string containing keys and values into array

Tags:

arrays

string

php

does anyone know an elagant way of turning this string (the list is not definite.. the "keys" and "values" can be added arbitrarily)

business_type,cafe|business_type_plural,cafes|sample_tag,couch|business_name,couch cafe

into this array?

array(
     [business_type]=>'cafe'
     [business_type_plural] => 'cafes'
     [sample_tag]=>'couch'
     [business_name]=>'couch cafe'
     )
like image 634
ondrobaco Avatar asked Oct 27 '10 12:10

ondrobaco


1 Answers

Explode it!

$string = "business_type,cafe|business_type_plural,cafes|sample_tag,couch|business_name,couch cafe";

$finalArray = array();

$asArr = explode( '|', $string );

foreach( $asArr as $val ){
  $tmp = explode( ',', $val );
  $finalArray[ $tmp[0] ] = $tmp[1];
}

print_r( $finalArray );

This will output the following:

Array
(
    [business_type] => cafe
    [business_type_plural] => cafes
    [sample_tag] => couch
    [business_name] => couch cafe
)
like image 160
Harmen Avatar answered Sep 19 '22 23:09

Harmen