[thelist] Php array, best way to...

Michael Pemberton evolt at mpember.net.au
Sun Jul 11 05:38:46 CDT 2004


jsWalter wrote:

> I have an array with 100+ elements
> 
> Each element is an array of 75 elements
> 
> What would be the best way to retrieve a subset of elements from each
> the sub-array?
> 
> Say I wanted element 2 thru 6, 11 and 42 from each element of the main
> array?
> 
> How would you go about this?
> 
> ============
> 
> Now to ask the question using terms like 'row' and column'.
> 
> Yes, I know, PHP arrays are not rows and columns. They are index arrays
> that can hold arrays in each "value" of the array.
> 
> I want column 2 thru 6, 11 and 42 from each row.
> 
> How would you go about this?
> 
> =============
> 
> Right now, I pull each element out and stick it in a second array...
> 
>   $tmpArray = array()
> 
>    for ( $i = 0; $i < $mainArrayCount; $i++ )
>    {
>       $tmpArray [$i][] = $rec[2];
>       $tmpArray [$i][] = $rec[3];
>       $tmpArray [$i][] = $rec[4];
>       $tmpArray [$i][] = $rec[5];
>       $tmpArray [$i][] = $rec[6];
>       $tmpArray [$i][] = $rec[11];
>       $tmpArray [$i][] = $rec[42];
>    }
> 
> Is there a better way?
> 
> Thanks
> 
> Walter
> 
> 

Look at using the array_slice function.  It will return a subset of the 
array contents as it's own array.  you could then use array_merge to 
append it to your tmpArray.

eg.

     for ( $i = 0; $i < $mainArrayCount; $i++ ) {
        array_push($tmpArray[$i], array_splice($rec, 2,5);
        array_push($tmpArray[$i], array_splice($rec, 11,1);
        array_push($tmpArray[$i], array_splice($rec, 42,1);
     }

note: the PHP documentation warns that using the array_push and 
array_join functions are not intended to be used with single values. 
They suggest the use of your original approach if you are only doing 
single values.

How often is the number/keys of the extracted calues going to change? 
If they are variable, then I would suggest possibly combining your 
original function approach with one that compares the second array's key 
to a set or numbers you can set at runtime.

hth

-- 
Michael Pemberton
evolt at mpember.net.au





More information about the thelist mailing list