This is not the explode
can solve
I have several array
$order
data: {5,3,2}
$title,
data: {USA, England, China}
$attribute
Same idea
$type
Same idea
The $order has already exist some value
{5,3,2} and
for each has its $title,$attribute,$type value correspondingly
eg. 5 USA att5 type5
I would like to sort the order to {2,3,5} and the corresponding data in other array will be sorted too.
eg. {2,3,5}
For the array $title afterwards
is
{China, England,USA}
How to implement this for all arrays? Thank you
My idea is using an associative array , and i can sort the key, and everything is done. However, I can not generate the array
My idea array:
$records = array(5 => array("title" => "USA", "att" => "add5"),
3 => array("title" => "England", "att" => "add3"),
2 => array("title" => "China", "att" => "add2"));
5 Answers 5
<?php
$order = array(5, 3, 2); // or $order = array("5", "3", "2");
$title = array("USA", "England", "China");
$att = array("Att 1", "Att 2", "Att 3");
$type = array("Type 1", "Type 2", "Type 3");
$records = array();
foreach ($order as $i => $o)
$records[$o] = array("title" => $title[$i], "att" => $att[$i], "type" => $type[$i]);
ksort($records, SORT_NUMERIC);
print_r($records);
?>
Comments
After these lines on your script
$string = substr($string, 0, -1);
$records="array (".$string.");";
You can add
eval("\$records = $records;");
You can read about the eval function at http://php.net/manual/es/function.eval.php and why you should be really careful when using it
7 Comments
eval
eval
being practical, please, reconsider... can you be sure what outcome will it do when input (even slightly) changes?where one explode
is not enough, two explode
s can help ;)
$records = Array();
foreach(explode("\n", trim($string)) as $line)
{
list($order,$title,$attribute,$type) = explode(",", $line);
$records[$order] = Array("title" => $title, "attribute" => $attribute, "type" => $type);
}
ksort($records);
3 Comments
$order,$title,$attribute,$type
. if not, then consider a different approach.multisort
.things are now more clear
for this i recommend using array_multisort
http://php.net/manual/en/function.array-multisort.php
2 Comments
instead of converting from a string to array you can build it
$result = array();
$countItem=0;
foreach ($order as $itemID)
{
$result [$countItem] = array('id' => $itemID, 'title' => $title[$countItem], 'attribute' => $att[$countItem],'type'=>$type[$countItem]);
$countItem++;
}
and then sort it by id
8 Comments
$title[$countItem]
...