Php array function
array1 = Array
(
[0] => Array
(
[direction_id] => 3
[direction_name] => Hamza
[direction_type_name] => Metro
)
[1] => Array
(
[direction_id] => 4
[direction_name] => Alisher Navoiy
[direction_type_name] => Metro
)
[2] => Array
(
[direction_id] => 2
[direction_name] => Bunyodkor
[direction_type_name] => Metro
)
[3] => Array
(
[direction_id] => 1
[direction_name] => Skver
[direction_type_name] => Orienter
)
[4] => Array
(
[direction_id] => 6
[direction_name] => Mustaqillik maydoni
[direction_type_name] => Orienter
)
[5] => Array
(
[direction_id] => 5
[direction_name] => Bobur parki
[direction_type_name] => Orienter
)
)
I have array1 array. I want change this array like this:
array1 = Array
(
[Metro] => Array
(
[direction_id] => 3
[direction_name] => Hamza
[direction_id] => 4
[direction_name] => Alisher Navoiy
[direction_id] => 2
[direction_name] => Bunyodkor
)
[Orienter] => Array
(
[direction_id] => 1
[direction_name] => Skver
[direction_type_name] => Orienter
[direction_id] => 6
[direction_name] => Mustaqillik maydoni
[direction_id] => 5
[direction_name] => Bobur parki
开发者_StackOverflow中文版 )
)
How can I do it?
You can't like that. You can't repeat keys. They need to be unique.
You probably want something like this:
[Metro] => Array
(
0 => array(
[direction_id] => 3
[direction_name] => Hamza
),
1 => array(
[direction_id] => 4
[direction_name] => Alisher Navoiy
)
...
What you need to do is use the foreach
construct to loop your original array and reorganize the data the way you want to.
... or wait for someone to post the exact code you need in one of the answers.
Try this:
<?php
$resultArray = array();
for($i = 0; $i < count($array1); $i++) {
if(!array_key_exists($array1[$i]['direction_type_name'], $resultArray) {
$resultArray[$array1[$i]['direction_type_name']] = array();
}
$resultArray[$array1[$i]['direction_type_name']][] = array('direction_id' => $array1[$i]['direction_id'], 'direction_name' => $array1[$i]['direction_name']);
}
print_r($resultArray);
?>
Didn't test it, but hope it works...
you cant really do that, because you cant have 2 keys being the same per array, but what you can do is:
$newArray = array();
foreach($array1 as $val){
if(!isset($newArray[$val['direction_type_name']])){
$newArray[$val['direction_type_name']] = array();
}
$newArray[$val['direction_type_name']][] = array(
'direction_id' => $val['direction_id'],
'direction_name' => $val['direction_name']
)
}
it would end up being something like
$newArray = Array (
[Metro] => Array
(
[0] => Array (
[direction_id] => 3
[direction_name] => Hamza
)
[1] => Array (
[direction_id] => 4
[direction_name] => Alisher Navoiy
)
...
I think you can do something simple like an iteration over your big array: You create 2 other arrays : Metro and Orienter For all item in your big array : if direction_type_name == Metro, then you add the informations to the Metro array, otherwise you add the information to Orienter array
精彩评论