简体   繁体   中英

creating a multidimensional array from arrays in php

I'm trying to create an array of bar objects in php which consist of seven different attributes. The code I am using for this array is as follows:

$barsArray = array();

    for($i = 0; $i < count($barNameArray); $i++)
    {
        $barsArray[] = array('BarName' => $barNameArray[$i], 'first' => $firstCover[$i], 'timeFirst' => $firstTimes[$i], 
                                                                'second' => $secondCover[$i], 'timeSecond' => $secondTimes[$i], 
                                                                'third' => $thirdCover[$i], 'timeThird' => $thirdTimes[$i]);
    }

I have checked to make sure that all the other arrays are as I intend them. I just need to get this into one array of objects. Is this method completely off? Also, If I wanted to test to make sure that the correct objects are in the correct locations in a multidimensional array, how would I go about do that?

Thanks!

That code looks fine (although you may want to cache the count instead of performing it repeatedly).

I can't say for sure, not knowing your greater purpose, but you may want to make $barsArray an associative array by the bar name. To do that, use $barsArray[$barNameArray[$i]] = , instead of $barsArray[] = (and of course remove the BarName property). This would not keep it in the original ordering, but would make getting a particular bar easier.

You can get an element from $barsArray like so: $barsArray[3]['first'] (or $barsArray['some_bar_name']['first'] if you change it to an associative array).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM