PHP: flatten multidimensional array
-
10-07-2019 - |
Question
I need to explode by "," then ":". Easy enough...
$alttitle = "35:title1,36:title2, 59:title5"
$replacetitles = explode(",",$alttitle);
for ($i = 0 ; $i < count($replacetitles) ; $i++) {
$replacetitle[] = explode(":", $replacetitles[$i]);
}
Which produces...
Array ( [0] => Array ( [0] => 35 [1] => title1 ) [1] => Array ( [0] => 36 [1] => title2 ) [2] => Array ( [0] => 59 [1] => title5 ) )
...but the number 35,36,59 are unique so I want this to become the key for the array?
Array ( [35] => title1 [36] => title2 [59] => title5 )
Solution
Simply set it while looping:
$alttitle = "35:title1,36:title2, 59:title5"
$tmptitles = explode(",",$alttitle);
$replacetitle = array();
foreach($tmptitles as $tmptitle) {
$tmparr = explode(":", trim($tmptitle));
$replacetitle[intval($tmparr[0])] = trim($tmparr[1]);
}
With the above, you will create your array a minimum number of iterations.
OTHER TIPS
Here is another but probably overkill alternative.
if (!preg_match_all('/([0-9]+)\s*:\s*([^,]+)/', $alttitle, $matches)) {
//not valid
}
$array = array_combine($matches[1], $matches[2]);
print_r($array);
Here's my take
$alttitle = "35:title1,36:title2, 59:title5";
$entries = preg_split( "/ *, */", $alttitle );
$flattened = array();
for ( $i = 0, $l = count( $entries ); $i < $l; $i++)
{
list( $index, $value ) = explode( ':', $entries[$i] );
$flattened[$index] = $value;
}
print_r( $flattened );
EDIT
Now with speed test vs explode/trim
$testData = implode( ',', array_fill( 1, 10000, "a,b, c, d" ) );
$start = microtime( true );
$entries = explode( ",", $testData );
$ouptput = array();
for ( $i = 0, $l = count( $entries ); $i < $l; $i++ )
{
$output[] = trim( $entries[$i] );
}
echo "explode/trim test took: ", ( microtime( true ) - $start ), ' seconds<br>';
unset( $start, $entries, $output );
$start = microtime( true );
$entries = preg_split( "/ *, */", $testData );
$ouptput = array();
for ( $i = 0, $l = count( $entries ); $i < $l; $i++ )
{
$output[] = $entries[$i];
}
echo "preg_split test took: ", ( microtime( true ) - $start ), ' seconds<br>';
After your code you can add this:
$ar = array();
for ($i = 0; $i < count($replacetitle); $i++) {
$ar[$replacetitle[$i][0]] = $replacetitle[$i][1];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow