php - combine keys, values from different arrays within a string -
bare me, tricky 1 put in title :)
i have string looks this:
$input_string = '<script>some data = { first: [[111,55],[123,66]], thecolor: "#000000", second: [[111,95],[123,77]] }; </script>'
as can see, complex string, possible garbage, 2 arrays mixed in. arrays first dimension same in each array, ie, '111' , '123' - should key new array created.
so need build new arrays, using key/value pair , produce first one:
array() { '111' => array(2) { 'first' => string(2) "55" 'second' => string(2) "95" } }
i hope thats clear :)
thanks
i used regex in order extract key , values in 2 separated arrays.
see demo.
<?php $re = "/(\\[?(?:\\[(\\d{1,}),(\\d{1,})\\]))/"; $str = '<script>some data = { first: [[111,55],[123,66]], thecolor: "#000000", second: [[111,95],[123,77]] }; </script>'; preg_match_all($re, $str, $matches); $output = array(); for($i = 0; $i < count($matches); ++$i) { // if key exists - push if(isset($output[($matches[2][$i])])) array_push($output[($matches[2][$i])], $matches[3][$i]); // otherwise create array store possible future values. else $output[($matches[2][$i])] = array( 0 => $matches[3][$i]); } print "<pre>"; print_r($output); print "</pre>"; ?>
output :
array ( [111] => array ( [0] => 55 [1] => 95 ) [123] => array ( [0] => 66 [1] => 77 ) )
ezy pezy lemon squizzy.
Comments
Post a Comment