Page 1 of 1

Array trouble

Posted: Fri Dec 17, 2004 11:39 pm
by Steveo31
Hey all, few questions.. first off, this is the basic structure of my arrays:

Code: Select all

<?php

$array1 = array(
            "SubArray1" => array("one", "two")
          , "SubArray2" => array("one_a", "one_b")
          );
          
$array1 = array(
            "01" => array("001", "002")
          , "02" => array("003", "004")
          );

?>
Basically it's my version for making product id's. So "SubArray1" -> "two" would have the value "01-002". Buuut, I can't seem to get the coding right for this. I'm sure it has some combo of foreach() and for(), but all attempts in the last 2 days have failed. Any advice is greatly appreciated.

Thanks :)

Posted: Sat Dec 18, 2004 1:44 am
by rehfeld
i know it can be confusing

well you can do it 2 ways, it depends if you want to use numerically indexed arrays, or associative arrays, or even a combo

remember, associative arrays are extremely similar to folders on your computer. that might help you visualize things.
a folder being an array, a file being a value. folders can contain both files(values) and folders(nested arrays)


dont forget commas after nested arrays


picture building the array in steps

you start w/

Code: Select all

$foo = array(
    'value1',
    'value2',
);

// then to expand it, visualize pasting another array in place of value

$foo = array(
    array(),
    array(),
);

// and if you need it to be associative, like wanting to name a category array

$foo = array(
    'category 1 name' => array(),
    'category 2 name' => array(),
);

// and then you just repeat and go as deep as your brain can comprehend 


$foo = array(
    'category 1 name' => array(
        'value1',
        'value2',
    ),
    'category 2 name' => array(
        'value1',
        'value2',
    ),
);

$foo = array(
    'category 1 name' => array(
        'value1' => array(),
        'value2' => array(),
    ),
    'category 2 name' => array(
        'value1' => array(),
        'value2' => array(),
    ),


);

Code: Select all

<?php
// associative
$tree_trunks = array(

    'trunk1' => array(

        'branch1' => array(
            '001', // notice this is not an associative array, but u could make it one if u want
            '002'
        ),

        'branch2' => array(
            '001',
            '002'
        ),

    ),


    'trunk2' => array(

        'branch1' => array(
            '001',
            '002'
        ),

        'branch2' => array(
            '001',
            '002'
        ),

    ),

);


foreach ($tree_trunks as $trunk => $branches) { // associative
    echo "$trunk<br>\n";
    
    foreach ($branches as $branch => $twigs) { // associative
        echo "----$branch<br>\n";
        
        foreach ($twigs as $twig) { // numerically indexed
            echo "--------$twig<br>\n";
        }
        
    }
    
}


?>

Posted: Sat Dec 18, 2004 3:46 am
by Steveo31
Cool, thanks for that. Quite helpful. But I think what I'm after is like a foreach(), but that will accept more than one array value. Here's what I came up with:

Code: Select all

function get_code($main, $sub){
    $num_categories = array(
                "060" => array("501", "502", "503", "504", "505", "506")
                , "70" => array("507", "508", "509", "510")
                , "80" => array("511", "512", "513", "514", "515", "516")
                , "90" => array("517", "518")
                , "100" => array("519", "520", "521", "522")
                , "200" => array("523", "524", "525", "526")
                , "300" => array("548", "549", "550", "551")
                , "400" => array("527", "528", "529")
                , "500" => array("530", "531", "531", "532", "533")
                , "600" => array("534", "535", "536", "537", "538", "539", "540")
                , "700" => array("541")
                , "800" => array("542", "542", "543", "544")
                , "900" => array("545", "546", "547")
            );

    $categories = array(
              "Furniture" => array("Art", "Pictures", "Antiquities", "Item Managers", "Decoration", "Movable")
             , "Family" => array("Toys", "Motherhood", "Jewels and Perfumes", "Pharmacy")
             , "Tools" => array("Tools", "Heavy Equipment", "Generators", "Pro Equipment", "Rentals", "Agricultural Tools")
             , "Animals" => array("Accessories", "Bedding")
             , "Real Estate" => array("Commerce", "Business", "Residential", "Industrial/Machine")
             , "Hardware" => array("Electrical", "Plumbing", "Electrical", "Sanitation")
             , "Education" => array("Books", "Computers", "Printers/Peripherals", "School/Office Supplies")
             , "Data Processing" => array("Software", "Games", "Computer Accessories")
             , "Electronics" => array("Audio", "Video", "Video Game Consoles", "Phones", "Cell Phone Accessories")
             , "Leisures" => array("Sports Equipment", "Photography", "Music", "Musical Instruments", "Movies", "Collections", "Hobbies")
             , "Community" => array("Sharing")
             , "Automobiles" => array("Directories", "Accessories", "Cars", "Equipment")
             , "Employment" => array("Job Fairs", "Seminars", "Frameworks")
         );
    while((list($key, $value) = each($categories)) && (list($key_num, $value_num) = each($num_categories))){
        echo $key.":  ".$key_num."<br />";
        if($key == $main){
            $foo = $key_num;
        }
        while((list($subkey, $subvalue) = each($value)) && list($subkey2, $subvalue2) = each($value_num)){
            echo "--".$subvalue.":  $subvalue2<br />";
            if($subvalue == $sub){
                $bar = $subvalue2;
            }
        }
        $both = $foo.": ".$bar;
        return $both;
    }
}
echo get_code("Furniture", "Art");
This gives me "060: 501". However, when I change the parameters, it throws an error that $foo and $bar aren't defined.

Long code, but basic basis. Any ideas on a fix?

Posted: Sat Dec 18, 2004 8:25 am
by timvw

Code: Select all

foreach($categories as $category => $subcategories)
{
    echo "$category <br/>";
   foreach($subcategories as $subcategory)
    {
               echo "$subcategory <br/>";
     }
}

Posted: Sun Dec 19, 2004 2:18 am
by Steveo31
timvw wrote:

Code: Select all

foreach($categories as $category => $subcategories)
{
    echo "$category <br/>";
   foreach($subcategories as $subcategory)
    {
               echo "$subcategory <br/>";
     }
}
Yep, had it for a while, but I needed something like a foreach that would accept multiple arrays :-/

What I eventually need is a function that takes 2 parameters. One will be the main category, i.e. "Real Estate" and the other will be the subcategory, like "Business", and the function will return, basically, those element's positions in the $num_categories array, so "100" and "520". Kinda see what I mean? Confusing I know :)

Posted: Sun Dec 19, 2004 5:09 pm
by rehfeld
foreach accepts an array.


an array can contain an array


think about that....

Code: Select all

// look, this has 3 arrays in it
$arrays = array(
     array(),
     array(),
     array(),
);

// heres your foreach that accepts multiple arrays
foreach ($arrays as $sub_array) {
    // now traverse the sub_arrays w/ another foreach
}

i see why your prob trying to split things up into 2 arrays, because deeply nested sub arrays are prob confusing you, which is normal.

but imo i think you should not split things into multiple arrays like that. trying to traverse 2 arrays at the same time and hoping your indices match up is asking for trouble.


i showed you some examples of how to traverse nested arrays, and so has timvw.

Posted: Sun Dec 19, 2004 10:22 pm
by Steveo31
Phew...ok, thanks. Yea, I figured it was a lot to be asking, and wasn't really possible. I'll re-asses my array structure and get back to you guys. Thanks :)

Posted: Sun Dec 19, 2004 10:59 pm
by Appletalk
Why don't you store the categories in a XML file?
It'd simpler and reusable, as you can add the categories by modifying a text file.

Posted: Mon Dec 20, 2004 1:08 am
by timvw
What is exactly simpler? imho iterating over an array or an xml file is just as difficult... Actually, if i look at simplexml etc i even get the impression that people prefer to loop over an array more than do the xml parsing...

Why is xml more reusable than an array in a php environment?

Adding to categories by modifying a text file goes the same for a php script (as already proven by the OP)

Except that it's "cool" to use xml (and introduces a lot of bloated overhead) i don't see a valid reason...