I have a multidimensional array which I want to convert to individual arrays.
Original array is
$hos_pabsl = array(
0 =>
array(
'tile_id' => '1',
'tile_type' => '4',
'title' => 'Introduction',
'topicNum' => '1',
'topicTitle' => 'Introduction',
'subNum' => NULL,
),
1 =>
array(
'tile_id' => '2',
'tile_type' => '9',
'title' => 'Beer',
'topicNum' => '2',
'topicTitle' => 'Beer',
'subNum' => NULL,
),
2 =>
array(
'tile_id' => '3',
'tile_type' => '4',
'title' => 'Methods of Brewing',
'topicNum' => '2',
'topicTitle' => 'Beer',
'subNum' => NULL,
),
3 =>
array(
'tile_id' => '4',
'tile_type' => '11',
'title' => 'Beer Styles',
'topicNum' => '2',
'topicTitle' => 'Beer',
'subNum' => '',
),
);
I want to convert this array into individual arrays named 'tile_id' , 'tile_type' , ...
.
Currently I am doing it the following way !
$tile_id = [];
$tile_type = [];
$title = [];
$topicNum = [];
$topicTitle= [];
$subNum = [];
foreach($hos_pabsl as $val){
array_push($tile_id, $val['tile_id']);
array_push($tile_type, $val['tile_type']);
array_push($title, $val['title']);
array_push($topicNum, $val['topicNum']);
array_push($topicTitle, $val['topicTitle']);
array_push($subNum, $val['subNum']);
}
Problem 1: IS this the most efficient way (in terms of speed) to do this operation?
Problem 2:
The $hos_pabsl
array's index (or keys) are always going to be sequential. However, my problem is that for second array (at level 2 OR $hos_pabsl[0]) the index (or keys) might increase or decrease.
E.g. all arrays in might have only 2 items 'tile_id' & 'title'. OR might have one extra item 'description'. So how can I make the above operation dynamic ?
To Solve problem 2, I have thought of using array_keys to extract names first $names = array_keys($hos_pabsl[0])
then using those names as array names like ${$names[0]} =[]
. Again I don't think this is the right/efficient way to do this.
Any guidance on this would be really appreciated.
$tile_id=Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4);
and$title = Array ( [0] => Introduction [1] => Beer [2] => Methods of Brewing [3] => Beer Styles);
and$topicTitle = [0] => Introduction [1] => Beer [2] => Beer [3] => Beer);
and so on and so forth.. I am getting the original array from DB and I need individual array for separate unrelated processing in different functions. – phpLearner May 1 '14 at 23:36