1

The html select code generated by using (wp_dropdown_categories) WordPress function and i want to convert it into an array urgently.

<select name="selectname1" id="selectId1" class="postform">
<option value="0">Recent Posts</option>
<option class="level-0" value="1">Uncategorized</option>
<option class="level-0" value="2">World News</option>
<option class="level-1" value="3">&nbsp;&nbsp;&nbsp;Political</option>

So i need to be something like that (Key, Value)

Array('Recent Posts' => '0',
'Uncategorized' = > '1',
'World News' = > '2',
'&nbsp;&nbsp;&nbsp;Political' = > '3'
);
3
  • If there are just 4 items, why not simply do it by hand? Commented Aug 27, 2013 at 5:55
  • So are you parsing html, or do you have access to the wp_dropdown_cats? Commented Aug 27, 2013 at 5:56
  • it's a dynamic list, could have hundred items Commented Aug 27, 2013 at 6:01

2 Answers 2

1

Try this:

$list = explode('</option>', $s);
foreach ($list as $v)
  $result[] = strip_tags($v);
Sign up to request clarification or add additional context in comments.

Comments

1

Since you want it quickly, here's a quick-n-dirty regex solution:

$matches = null;
$result = array();

if(preg_match_all('/value="(.*)".*?>(.*)<\\/option>/', $s, $result)){
    $matches = array_pop($matches);
    foreach($matches[1] as $i => $key){
        $key = html_entity_decode($key);
        $val = html_entity_decode($matches[2][$i]);
        $result[$key] = $val;
    }
}

print_r($result);

However, you really should not tokenise/parse HTML with regular expressions, instead use an XML/DOM class.

1 Comment

Thanks man so much, but the array repeated 3 times ** Array ( [0] => Array ( [0] => value="0">Recent Posts [1] => value="1">Uncategorized [2] => value="2">World News [3] => value="3"> Political [4] => value="4"> Economy ) [1] => Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 ) [2] => Array ( [0] => Recent Posts [1] => Uncategorized [2] => World News [3] => Political [4] => Economy ) ) ** can u help me with XML/DOM ??

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.