0

I have a table that holds user data in a single row and it looks like this

enter image description here

What I am trying to do is list them in order of their priority so the outcome looks like this

Everything (because its priority is 1)
Something (Because its priority is 2)
Anything (Because its priority is 3)

At present to achieve this I am using else if statement and it is working fine for example

if (Data1_Priority == '1'){
echo Data1
}elseif{
.....
}

I was wondering if it is possible to display the data in order of their priority using some loop rather than if else

I will really appreciate any assistance on how to achieve this.

1
  • 2
    1. See normalisation Commented Nov 4, 2014 at 12:31

3 Answers 3

1

Do you want to unpivot them and sort them?

select d.*
from (select data1 as data, data1priority as priority from table union all
      select data2 as data, data2priority as priority from table union all
      select data3 as data, data3priority as priority from table
     ) d
order by priority;

As a note: having similar column names that only differ by a number is a sign of poor database design. It is usually better to have fewer columns and more rows.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, your solution solved the problem, columns in actual table do not differ my number only, i used an example to make it easier to understand what i a trying to achieve. Once again many thanks
1

As mentioned by others, you should be doing this in the database (probably with a redesign), but for a php solution, you can create a temporary array indexed by priority, sort on the key, then iterate it:

$row = [
    'data1'=>'something',
    'data1_priority'=>2,
    'data2'=>'anything',
    'data2_priority'=>3,
    'data3'=>'everything',
    'data3_priority'=>1,

];
$temp=[];

for($i=1; $i<(count($row)/2)+1; $i++){
    $temp[$row['data'.$i.'_priority']]=$row['data'.$i];
}
ksort($temp);
foreach($temp as $element)
    echo $element . '<br>';

Live example: http://codepad.viper-7.com/O3D54e

Comments

0
for ($pri = 1; $pri<=3; $pri++)
{
    for($d == 1; $d<=3; $d++)
    {
        if ($r["Data".$d."_Priority"] == $pri)
        {
           echo $r["Data".$d];
        }
    }
}

Untested, but a point in the right direction?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.