Page 1 of 1

Reorder a string to move one item to the front

Posted: 09 Mar 2018 14:16
by klownboy
Hi, I'm hoping to find a more direct or possibly smarter way to reorder a string slightly - to move one item to the front of the string. I first determine which item in the string I want to be accomplished first. Then I want to move that item to the front of the string list before a subsequent foreach loop. I don't care about the order of the the items just the one I've determined - that one must be first in the list. I want to accomplish this independently and not within a complicated series of three nested foreach loops which comes in the next lines of code (too much going on in that already). So for example, I have a string list of items; AA, BB, CC, DD. I've predetermined in this case BB must be first, but that could change in every situation. The string list would be for example, AA<crlf>BB<crlf>CC<crlf>DD.

Currently (the only way I came up with) is using a separate foreach loop where I look to see if one of those items equals another predetermined value(e.g., if($the_one_and only == BB)). If it does, I build a new listing in the loop with the one matching having a "_0" in front of it and the others do not. Then I SC formatlist the string list to get the one desired up front and trim the leading '_0' out. The end result would be BB<crlf>AA<crlf>CC<crlf>DD. It works, but seems a bit cumbersome. Any other ideas possibly. I can provide the actual code if necessary. It involves thumbnail size and views in particular thumbnail sizes. Thanks.

Re: Reorder a string to move one item to the front

Posted: 09 Mar 2018 14:25
by jupe
I am not a coder, so should probably not be commenting on this, but here is a very hackish way, I think I am understanding your criteria.

Code: Select all

	$string = "AA<crlf>BB<crlf>CC<crlf>DD";
	$string = "BB<crlf>" . replace($string, "BB<crlf>");
	echo $string;
It's probably nothing like what you want though.

Re: Reorder a string to move one item to the front

Posted: 09 Mar 2018 14:32
by highend
@Ken, something like this?

Code: Select all

    text Reorder("AA<crlf>BB<crlf>CC<crlf>DD", "BB");

    function Reorder($string, $sub, $sep=<crlf>) {
        return formatlist(gettoken($string, gettokenindex($sub, $string, $sep, "i"), $sep) . $sep . replace($string, $sub, , , , 1), "e", $sep);
    }

Re: Reorder a string to move one item to the front

Posted: 09 Mar 2018 16:04
by klownboy
Thanks guys, It's been one of those days. I was really blocked on a better idea. I was trying SC replacelist but it wasn't working out for me. Using SC replace is fast and simple. Certainly better than using a foreach loop. Thanks again.