I need an array with entries for different industries then inside that different professions then inside that headings for different attributes such as “knowledge”, “skills”, “abilities”. Then entries under each heading. This page gives an example of one entry: Picker and Packer
Here is the code for the associative array I have so far. I am surprised I had to use four )’s just to stop getting error messages. Have I done this correctly? Is there a way I can make this code cleaner and easier to read? Thank you.
<?php $indus['agriculture'] = array( "Picking and Packing" => array("Tasks" => array("entry1", "entry2", "Entry3", "Entry4", "Entry5"), "Tools_used" => array("Entry1", "Entry2", "Entry3","Entry4", "Entry5"), "Knowledge" => array("Entry1", "Entry2"), "Skills" => array("Entry1","Entry2"), "Abilities" => array("Entry1", "Entry2", "Entry3","Entry4", "Entry5"), "Farm Worker" => array("Tasks" => array("Entry1","Entry2","Entry3"), "Tools_used" => array("Entry1","Entry2","Entry3"), "Knowledge" => array("Entry1","Entry2"), "Skills" => array("Entry1","Entry2"), "Abilities" =>array("Entry1, Entry2"), "Agricultural Equipment Operator" => array("Tasks" => array ("Entry1","Entry2"), "Tools_used" => array("Entry1","Entry2"), "Knowledge" => array("Entry1.","Entry2"), "Skills" => array("Entry1","Entry2"), "Abilities" =>array("Entry1","Entry2") ))) );?>
Advertisement
Answer
PHP 5.4 introduced the array short-hand []
, which IMHO makes arrays easier to write and read. PHP also allows for trailing commas in arrays which makes adding values easier because you don’t have to worry about them messing up and throwing syntax errors.
<?php $indus['agriculture'] = [ "Picking and Packing" => [ "Tasks" => [ "Entry1", "Entry2", "Entry3", "Entry4", "Entry5", ], "Tools_used" => [ "Entry1", "Entry2", "Entry3", "Entry4", "Entry5", ], "Knowledge" => [ "Entry1", "Entry2", ], "Skills" => [ "Entry1", "Entry2", ], "Abilities" => [ "Entry1", "Entry2", "Entry3", "Entry4", "Entry5", ], ], "Farm Worker" => [ "Tasks" => [ "Entry1", "Entry2", "Entry3", ], "Tools_used" => [ "Entry1", "Entry2", "Entry3", ], "Knowledge" => [ "Entry1", "Entry2", ], "Skills" => [ "Entry1", "Entry2", ], "Abilities" => [ "Entry1", "Entry2", ], ], "Agricultural Equipment Operator" => [ "Tasks" => [ "Entry1", "Entry2", ], "Tools_used" => [ "Entry1", "Entry2", ], "Knowledge" => [ "Entry1", "Entry2", ], "Skills" => [ "Entry1", "Entry2", ], "Abilities" => [ "Entry1", "Entry2", ], ], ];
More lines since it’s unpacked and each child given its own line, but more readable than using array()
. Each worker type is also easily accessible using the keys, i.e.
print "<pre>"; print_r($indus['agriculture']["Agricultural Equipment Operator"]);