Insert into php array after certain value?
I have a string like this,
sidePanel[]=1&sidePanel[]=2&sidePanel[]=4
And if I need to add another value to the string I do this:
$sidePanel = explode('&', $_SESSION['sidePanel']);
array_push($sidePanel, 'sidePanel[]=3');
$sidePanel = implode('&', $side开发者_如何学JAVAPanel);
Which returns this:
sidePanel[]=1&sidePanel[]=2&sidePanel[]=4&sidePanel[]3
Now how can I make it so that it will always insert after the array 'sidePanel[]=2' when I explode it at &?
I do not want it in numerical order although this example will return it in numerical order, as the string can change to be in any order.
I cannot use array_splice as I understand this uses the key of the array, and as the position of sidePanel[]=2 can change it will not always be the same.
You can indeed use array_splice, but you have to find the position of your insertion point first:
$sidePanelArr = explode( '&', $_SESSION['sidePanel'] );
// find the position of 'sidePanel[]=2' in array
$p = array_search( 'sidePanel[]=2', $sidePanelArr );
// insert after it
array_splice( $sidePanelArr, p+1, 0, 'sidePanel[]=3' );
$sidePanelSt = implode( '&', $sidePanelArr );
You could also splice the string right into your original string without exploding and re-imploding. The function substr_replace() is your friend:
$sidePanelSt = $_SESSION['sidePanel'];
// find the position of 'sidePanel[]=2' in string
// (adding '&' to the search string makes sure that 'sidePanel[]=2' does not match 'sidePanel[]=22')
$p = strpos( $sidePanelSt.'&', 'sidePanel[]=2&') + strlen('sidePanel[]=2' );
// insert after it (incl. leading '&')
$sidePanelSt = substr_replace( $sidePanelSt , '&sidePanel[]=3' , $p, 0 );
See : http://codepad.org/5AOXcHPk
<?php
$str = "sidePanel[]=1&sidePanel[]=2&sidePanel[]=4";
$sidePanelArr = explode('&', $str);
$newVal = 'sidePanel[]=3';
$insertAt = 2 ;
$newArr = array_merge(array_slice($sidePanelArr, 0,$insertAt),
array($newVal),
array_slice($sidePanelArr,$insertAt)
);
$sidePanel = implode('&', $newArr);
echo $sidePanel,PHP_EOL ;
?>
You could turn it into an array using parse_str and locate the value you want to insert it after:
// Turn it into an array
$url = parse_str($_SESSION['sidePanel']));
// What value do we want to insert it after
$insert_after = 2;
// The value you want to insert
$sidePanel = 3;
// Find the position of $insert_after
$offset = array_search($insert_after, $url['sidePanel']);
// Slice the array up (based on the value)
$url['sidePanel'] = array_merge(array_slice($url['sidePanel'], 0, $offset),
array($sidePanel),
array_slice($url['sidePanel'], $offset));
// Turn it back into a string
echo http_build_query($url);
精彩评论