Jump to content

[SOLVED] Adding to multidimensional array


barrywood

Recommended Posts

I'm realtively new to PHP and I'm trying to get my head around a particular issue. I've got an array that looks like this:

 

$field_array = array (
array (field=>"dist_Company", type=>"text"),
array (field=>"dist_Active", type=>"select", options=>array(array(oname=>"yes", oval=>"1"), array(oname=>"no", oval=>"0"))),
array (field=>"dist_CompanyID", type=>"select"),
array (field=>"dist_Shipping", type=>"text")
);

 

What I'm trying to figure out is how to add to this array after it's been defined. In this case I'm trying to add the "options" subarray to dist_CompanyID element so that it has options similar to those predefined in the dist_Active element.

 

I can do it if I specify the index like this:

 

$field_array[2]['options'][] = array(oname=>"one", oval=>"1");
$field_array[2]['options'][] = array(oname=>"two", oval=>"2");
$field_array[2]['options'][] = array(oname=>"three", oval=>"3");

 

Is there some elegant way to find the index number for the element containing field=>"dist_CompanyID"?

 

TIA

Link to comment
https://forums.phpfreaks.com/topic/75579-solved-adding-to-multidimensional-array/
Share on other sites

I think you will need a custom search function for that one, such as my_array_search() below

<?php
$field_array = array (
array (field => "dist_Company", type=>"text"),
array (
                field => "dist_Active", 
                type => "select", 
                options => array(
                    array(
                        oname=>"yes", 
                        oval=>"1"), 
                        array(
                            oname=>"no", 
                            oval=>"0")
                )
          ),
array (field=>"dist_CompanyID", type=>"select"),
array (field=>"dist_Shipping", type=>"text")
);

$index = my_array_search("field", "dist_CompanyID", $field_array);

echo $index;

function  my_array_search($ind, $value, &$arr)
{
    for ($i=0, $k = count($arr); $i < $k; $i++)
    {
        if ($arr[$i][$ind] == $value) return $i;
    }
    return false;
}         
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.