0

I have a function that I want to generate an array with. The format of the array is specific and only values need to be changed based on the arguments of my function. Here's the function:

 function generatearray($name1, $field1, $name2, $field2) {
  $language = ($user->language) ? $user->language : 'und';
   $edit = array(
    $name1 => array(
     $language => array(
      0 => array(
       'value' => $field1,
     ),
    ),
   ), // ..... other elements $name2
  );
  return $edit;
}

$name2 and $field2 are optional arguments.

2
  • It may not answer your question, but you're not defining $user anywhere - you need to either pass it in as a parameter, or declare it as a global. Commented Sep 20, 2012 at 19:18
  • Thanks for the help! I ended up defining $user as a 5th argument. Commented Sep 20, 2012 at 20:42

1 Answer 1

1

Not sure what the question is...but this code will do exactly what you're wanting to know about...a way to build an array based on up to 2 name/value pairs provided to a function.

printarray(generatearray('name_one','field_one','name_two','field_two'));

function generatearray($name1, $field1, $name2 = null, $field2 = null) {
$new_array = array();
$language = isset($user->language) ? $user->language : 'und';
$new_array[$name1][$language] = $field1;
if (!is_null($name2) && !is_null($field2)) {
    $new_array[$name2][$language] = $field2;
}
return $new_array;
}

function printarray($arr) {
foreach ($arr as $user_key => $user_value) {
    echo "User: ".$user_key."<br />";
    foreach ($user_value as $language_key=>$language_value) {
        echo "Language: ".$language_value."<br />";
    }
}
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.