/    Sign up×
Community /Pin to ProfileBookmark

help with sort()

Okay, I am totally mixed up with this problem:

I need an array with various numbers:

[FONT=Courier New]$a = array(100, 5000, 200, 400, 2000, 10, 7500);[/FONT]

and a corresponding array with strings:

[FONT=Courier New]$b = array(“foo”, “bar”, “barfoo”, “foobar”, “hello”, “world”, “hello world”);[/FONT]

I need to sort the number array, so I do:

[FONT=Courier New]sort($a);[/FONT]

My problem is, now the strings in $d don’t correspond to the numbers in $a ? Is there a way to sort $b so it corresponds again with $a again?

to post a comment
PHP

4 Comments(s)

Copy linkTweet thisAlerts:
@shane_carrauthorAug 17.2006 — Okay, I found a solution, but it sure isn't the greatest. This is for the high scores for my game, so I need to add just one certain value. Here's the code, though:

[code=php]$score = 1000;
$name = "goodbye world";
$a = array(10, 100, 200, 400, 2000, 5000, 7500);//they're going to already be in order
array_push($a, $score);
sort($a);
$b = array("foo", "bar", "barfoo", "foobar", "hello", "world", "hello world");
foreach($a as $ak => $av){
if($av == $score && $a[$ak+1] != $score){
array_splice($b, $ak, 0, array($name));
break;
}
}[/code]


Is there anybody with a better solution?
Copy linkTweet thisAlerts:
@pcthugAug 17.2006 — Is there anybody with a better solution?[/quote]
Use a relational database rather then an array.

Or alternatively use keys in your arrays:
[code=php]<?php

$a = array("foo" => 100, "bar" => 5000, "barfoo" => 200, "foobar" => 400, "hello" => 2000, "world" => 10, "hello world" => 7500);

asort($a);

echo '<table>';

foreach($a as $key => $value)
{
echo "<tr><td>$key</td><td>$value</td></tr>n";
}

echo '</table>';

?>[/code]
Copy linkTweet thisAlerts:
@shane_carrauthorAug 18.2006 — The second idea is good, but the array is unserialized, and serialization doesn't store array keys ?
Copy linkTweet thisAlerts:
@NogDogAug 18.2006 — [code=php]
array_multisort($a, SORT_ASC, SORT_NUMERIC, $b);
[/code]
×

Success!

Help @shane_carr spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.6,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...