thebiglebowski11
thebiglebowski11

Reputation: 1461

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?

Upvotes: 0

Views: 450

Answers (1)

Borealid
Borealid

Reputation: 98559

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).

Upvotes: 1

Related Questions