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
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;
}         
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.