implode() order? [message #176294] |
Mon, 19 December 2011 20:13  |
Mike
Messages: 18 Registered: December 2010
Karma: 0
|
Junior Member |
|
|
How can I specify the order that an Array() is imploded? See code below:
<?php
$toImplode = Array(
1 => "Second",
0 => "First",
2 => "Third"
);
$finalString = implode(" - ", $toImplode);
echo "<p>" . $finalString . "</p>";
/* Results as "Second - First - Third"
* But I need it to be "First - Second - Third"
*/
?>
|
|
|
|
|
|
|
|
|
|
Re: implode() order? [message #176306 is a reply to message #176298] |
Tue, 20 December 2011 01:55   |
Thomas 'PointedEars'
Messages: 701 Registered: October 2010
Karma: 0
|
Senior Member |
|
|
Mike wrote:
> Thanks... suppose the keys are not in a sortable order, like this:
>
> $toImplode = Array(
> "second" = "Second",
> "fourth" = "Fourth",
> "third" = "Third",
> "first" = "First"
> );
This is not PHP code.
> Or would I need to simply:
>
> echo $toImplode["first"] . $toImplode["second"]; // etc.
No, aside from u(k)sort() you can use a loop to build a new array:
$a = array();
foreach (array('first', 'second', 'third', 'fourth') as $key)
{
$a[] = $toImplode[$key];
}
echo implode(',', $a);
PointedEars
--
Prototype.js was written by people who don't know javascript for people
who don't know javascript. People who don't know javascript are not
the best source of advice on designing systems that use javascript.
-- Richard Cornford, cljs, <f806at$ail$1$8300dec7(at)news(dot)demon(dot)co(dot)uk>
|
|
|
Re: implode() order? [message #176307 is a reply to message #176305] |
Tue, 20 December 2011 03:34  |
Jerry Stuckle
Messages: 2598 Registered: September 2010
Karma: 0
|
Senior Member |
|
|
On 12/19/2011 8:59 PM, Thomas 'PointedEars' Lahn wrote:
> Thomas Mlynarczyk wrote:
>
>> Jerry Stuckle schrieb:
>>> Mike wrote:
>>>> Thanks... suppose the keys are not in a sortable order, like this:
> ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
>>>> $toImplode = Array(
>>>> "second" = "Second",
>>>> "fourth" = "Fourth",
>>>> "third" = "Third",
>>>> "first" = "First"
>>>> );
>>
>>> Use usort() and define your own comparison function.
>>
>> Rather u*k*sort() for sorting by keys:
>> http://de3.php.net/manual/en/function.uksort.php
>
> See the marked part.
>
> You should also post the (manual) URI that works best for the person using
> it, which would be
>
> <http://php.net/uksort>
>
> in this case.
>
>
> PointedEars
Who gives a damn what a troll thinks?
--
==================
Remove the "x" from my email address
Jerry Stuckle
JDS Computer Training Corp.
jstucklex(at)attglobal(dot)net
==================
|
|
|