Jump to content
php.lv forumi

string to array


aika

Recommended Posts

Uzdevums salādēt stringu arajā, taču pie nosacījuma ka rindas nekārtnais elements ir araja keys, bet kārtnais - vērtība.

Piemērs:

balts;2;melns;3;sarkans;5 => array('balts'=>2,'melns'=>3, 'sarkans'=>5)

 

Ja ērtāk, tad strings var būt arī: balts=2;melns=3;sarkans=5;

 

Šķietami vienkāršais uzdevums izrādījās nemaz tik viegls nav.

Link to comment
Share on other sites

array_filter() ftw

function odd($var){
static $c = 0;
return !(++$c%2);
}

function even($var){
static $c = 0;
return ++$c%2;
}

$str = 'balts;2;melns;3;sarkans;5';
$tmp = explode(';', $str);
$arr = array_combine(array_filter($tmp, 'odd'), array_filter($tmp, 'even'));

print_r($arr);
/*
Array
(
   [2] => balts
   [3] => melns
   [5] => sarkans
)
*/

Link to comment
Share on other sites

http://lv.php.net/manual/en/language.operators.increment.php

http://lv.php.net/manual/en/language.operators.arithmetic.php

http://lv.php.net/manual/en/language.operators.logical.php

 

++ -> pieskaita +1 un atgriež jauno vērtību

%2 -> atgriež dalījuma atlikumu

! -> atgriež pretējo boolean vērtību (ja dalījuma atlikums bija nulle (false), tad šis atgriež true)

Edited by marcis
Link to comment
Share on other sites

$string = 'balts=2;melns=3;sarkans=5;';
$array = array();
parse_str(str_replace(';','&',rtrim($string,';')), $array);

 

Ja ērtāk, tad strings var būt arī: balts=2;melns=3;sarkans=5;

Edited by indoom
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...