douhuocuo9012 2011-10-11 06:24
浏览 21
已采纳

某些值后插入php数组?

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('&', $sidePanel);

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.

  • 写回答

3条回答 默认 最新

  • duanbi6522 2011-10-11 06:58
    关注

    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 );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?