arrays - PHP Transformation string -
let's have array structure
$array = array(array('a' => 'a', 'x' => $something));
the variable $something can that: 1-3 or 1,3 or 1-3, 2-5. transform variable $array in:
case 1. $something = 1-3
$array = array(array('a' => 'a', 'x' => array(1,2,3)));
case 2. $something = 1,3
$array = array(array('a' => 'a', 'x' => array(1,3)));
case 3.. $something = 1-3, 2-5
$array = array(array('a' => 'a', 'x' => array(1,2,3,4,5)));
i tried utilize preg_match doesn't work. can give me hint utilize else?
you looking explode split input string, range generate array contents , array_merge merge result.
something works:
<?php $something = '1-3, 2-5'; $array = array(array('a' => 'a', 'x' => array())); $result = array(); foreach (explode(', ', $something) $input) { $rangeparts = explode('-', $input); $result = array_merge($result, range($rangeparts[0], $rangeparts[1])); } // contains duplicate entries because 1-3 , 2-5 overlap - utilize array_unique remove duplicates or alter input $array[0]['x'] = $result;
in lastly assignment can either wrap $result
in array_unique 1:1 match illustration or edit input ($something
) reflect inclusive/exclusive-rules of range function.
php arrays string
No comments:
Post a Comment