Jump to content

Creating a Multidimensional Array from an Array of Keys


mitchkill

Recommended Posts

Guys,

I am trying to create a class to interface with PayPal's invoicing API. The array that I will need to submit to them has a structure similar to the following:

 

Array
(
    [requestEnvelope] => Array
        (
            [detailLevel] => 
            [errorLanguage] => 
        )

    [invoice] => Array
        (
            [merchantEmail] => 
            [payerEmail] => 
            [number] => 
            [merchantInfo] => Array
                (
                    [firstName] => 
                    [lastName] => 
                    [businessName] => 
                    [phone] => 
                    [fax] => 
                    [webSite] => 
                    [customValue] => 
                    [address] => Array
                        (
                            [line1] => 
                            [line2] => 
                            [city] => 
                            [state] => 
                            [postalCode] => 
                            [countryCode] => 
                            [type] => 
                        )
                )
       )
)

 

I want to use PHP's magic method __set to be able to set values in the array like so:

 

$paypalObj->invoice_merchantInfo_firstName = "John";

 

To do this, I have created the following __set function within my class:

 

public function __set($name, $val) {
$nameArr = explode("_", $name);
$arr =& $this->request; // $this->request is the class property that holds the array
foreach($nameArr as $v) {
	if(isset($arr[$v]))
		$arr = &$arr[$v];
	else
		throw new Exception("Array key \$this->request[\"" . implode("\"][\"", $nameArr) . "\"] does not exist.");
}
$arr = $val;
}

 

The idea is that I split the variable name up via the underscore which gives me the name of the keys that I'll need to check for each depth of the multidimensional array. I then want to loop through the array of key names and append them to the working array so that I can determine if that is a valid array. However, this doesn't seem to work for me. When I try to build the array to check it (Line: $arr = &$arr[$v]; ), it's only returning the value of $arr[$v] and not the actual array itself. I need some way to be able to construct a multidimensional array using the array of keys, but I'm coming up empty so far. It seems like I'm missing something simple, but I can't figure it out. If you have any ideas, let me know! If you need clarifications, please ask. Thanks for your help!

Link to comment
Share on other sites

Are you meaning something like this?

 

<?php
$x = array(
     'a_b_c' => 1,
     'a_b_d' => 2,
     'a_c'   => 3
);

$res = array();

foreach ($x as $k => $v )
{
    $str = '$res[' . str_replace('_', '][', $k) . ']=' . $v . ';';
    eval($str);
}

echo '<pre>'.print_r($res, 1).'</pre>';
?>

 

result-->

Array
(
    [a] => Array
        (
            [b] => Array
                (
                    [c] => 1
                    [d] => 2
                )

            [c] => 3
        )

)


Link to comment
Share on other sites

Barand,
Thanks for the reply, but I'm really trying to stay away from eval. Too much can go wrong with it. I actually was given a solution on another board as follows:

public function __set($name, $val) {
        $nameArr = explode("_", $name);
        $lastName = array_pop($nameArr);
        $arr =& $this->request;
    
        for ($i = 0; $i < count($nameArr); $i++) {
            if(array_key_exists($nameArr[$i], $arr)) {
                if (!is_array($arr[$nameArr[$i]]))
                    throw new Exception("Array key \$this->request[" . implode("][", array_slice($nameArr, 0, $i)) . "] is not an array");
            } else
                throw new Exception("Array key \$this->request[" . implode("][",  array_slice($nameArr, 0, $i)) . "] is not a valid key.");

            $arr =& $arr[$nameArr[$i]];
        }
        if(array_key_exists($lastName, $arr))
            $arr[$lastName] = $val;
        else
            throw new Exception("Array key \$this->request[" . implode("][", $nameArr) . "] is not a valid key.");
    }  

 

The key was popping off the last value.

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.