php-general Digest 26 Feb 2013 21:28:06 -0000 Issue 8138

Topics (messages 320295 through 320300):

Re: Arrays
        320295 by: Adam Richardson
        320296 by: Jim Lucas
        320297 by: Karl DeSaulniers
        320298 by: Karl DeSaulniers
        320299 by: Karl DeSaulniers

Stupid question
        320300 by: Curtis Maurand

Administrivia:

To subscribe to the digest, e-mail:
        php-general-digest-subscr...@lists.php.net

To unsubscribe from the digest, e-mail:
        php-general-digest-unsubscr...@lists.php.net

To post to the list, e-mail:
        php-gene...@lists.php.net


----------------------------------------------------------------------
--- Begin Message ---
On Mon, Feb 25, 2013 at 8:40 PM, Karl DeSaulniers <k...@designdrumm.com> wrote:
> Hi Guys/Gals,
> If I have an multidimensional array and it has items that have the same name
> in it, how do I get the values of each similar item?
>
> EG:
>
> specialservices => array(
>         specialservice => array(
>                 serviceid => 1,
>                 servicename=> signature required,
>                 price => $4.95
>         ),
>         secialservice => array(
>                 serviceid => 15,
>                 servicename => return receipt,
>                 price => $2.30
>         )
> )
>
> How do I get the prices for each? What would be the best way to do this?
> Can I utilize the serviceid to do this somehow?
> It is always going to be different per specialservice.

Something appears to be amiss, as your array couldn't contain multiple
items with the specialservice key (I'm assuming the second key
'secialservice' is just a typo), as any subsequent assignments would
overwrite the previous value.

Adam

-- 
Nephtali:  A simple, flexible, fast, and security-focused PHP framework
http://nephtaliproject.com

--- End Message ---
--- Begin Message ---
On 02/25/2013 05:40 PM, Karl DeSaulniers wrote:
Hi Guys/Gals,
If I have an multidimensional array and it has items that have the same
name in it, how do I get the values of each similar item?

EG:

specialservices => array(
specialservice => array(
serviceid => 1,
servicename=> signature required,
price => $4.95
),
secialservice => array(
serviceid => 15,
servicename => return receipt,
price => $2.30
)
)

How do I get the prices for each? What would be the best way to do this?
Can I utilize the serviceid to do this somehow?
It is always going to be different per specialservice.

TIA,

Best,

Karl DeSaulniers
Design Drumm
http://designdrumm.com



This will never work. Your last array will always overwrite your previous array.

Here is how I would suggest building it:


$items = array(
    1 => array(
        serviceid => 1,
        servicename=> signature required,
        price => $4.95
    ),
    15 => array(
        serviceid => 15,
        servicename => return receipt,
        price => $2.30
    )
)

This will ensure that your first level indexes never overwrite themselves.

But, with that change made, then do this:

foreach ( $items AS $item ) {
  if ( array_key_exists('price', $item) ) {
    echo $item['price'];
  } else {
    echo 'Item does not have a price set';
  }
}

Resources:
http://php.net/foreach
http://php.net/array_key_exists

--
Jim Lucas

http://www.cmsws.com/
http://www.cmsws.com/examples/

--- End Message ---
--- Begin Message ---

On Feb 25, 2013, at 7:48 PM, Adam Richardson wrote:

On Mon, Feb 25, 2013 at 8:40 PM, Karl DeSaulniers <k...@designdrumm.com > wrote:
Hi Guys/Gals,
If I have an multidimensional array and it has items that have the same name
in it, how do I get the values of each similar item?

EG:

specialservices => array(
       specialservice => array(
               serviceid => 1,
               servicename=> signature required,
               price => $4.95
       ),
       secialservice => array(
               serviceid => 15,
               servicename => return receipt,
               price => $2.30
       )
)

How do I get the prices for each? What would be the best way to do this?
Can I utilize the serviceid to do this somehow?
It is always going to be different per specialservice.

Something appears to be amiss, as your array couldn't contain multiple
items with the specialservice key (I'm assuming the second key
'secialservice' is just a typo), as any subsequent assignments would
overwrite the previous value.

Adam

--
Nephtali: A simple, flexible, fast, and security-focused PHP framework
http://nephtaliproject.com


Hi Adam,
Actually you are correct. Sorry to confuse.
Its an XML response from the USPS api I am going through, which I am converting to an array.

Here is the response that I am trying to convert to a multidimensional array.

<?xml version="1.0"?>
<RateV4Response><Package ID="1ST"><ZipOrigination>75287</ ZipOrigination><ZipDestination>87109</ZipDestination><Pounds>70</ Pounds><Ounces>0</Ounces><Container>RECTANGULAR</ Container><Size>LARGE</Size><Width>2</Width><Length>15</ Length><Height>10</Height><Zone>4</Zone><Postage CLASSID="1"><MailService>Priority Mail&lt;sup&gt;&amp;reg;&lt;/ sup&gt;</MailService><Rate>62.95</ Rate><SpecialServices><SpecialService><ServiceID>1</ ServiceID><ServiceName>Insurance</ServiceName><Available>true</ Available><AvailableOnline>true</AvailableOnline><Price>1.95</ Price><PriceOnline>1.95</PriceOnline><DeclaredValueRequired>true</ DeclaredValueRequired><DueSenderRequired>false</DueSenderRequired></ SpecialService><SpecialService><ServiceID>0</ ServiceID><ServiceName>Certified Mail&lt;sup&gt;&amp;reg;&lt;/sup&gt;</ ServiceName><Available>true</Available><AvailableOnline>false</ AvailableOnline><Price>3.10</Price><PriceOnline>0</PriceOnline></ SpecialService><SpecialService><ServiceID>19</ ServiceID><ServiceName>Adult Signature Required</ ServiceName><Available>false</Available><AvailableOnline>true</ AvailableOnline><Price>0</Price><PriceOnline>4.95</PriceOnline></ SpecialService></SpecialServices></Postage></Package><Package ID="2ND"><ZipOrigination>75287</ZipOrigination><ZipDestination>87109</ ZipDestination><Pounds>55</Pounds><Ounces>0</ Ounces><Container>RECTANGULAR</Container><Size>LARGE</Size><Width>2</ Width><Length>15</Length><Height>10</Height><Zone>4</Zone><Postage CLASSID="1"><MailService>Priority Mail&lt;sup&gt;&amp;reg;&lt;/ sup&gt;</MailService><Rate>52.55</ Rate><SpecialServices><SpecialService><ServiceID>1</ ServiceID><ServiceName>Insurance</ServiceName><Available>true</ Available><AvailableOnline>true</AvailableOnline><Price>1.95</ Price><PriceOnline>1.95</PriceOnline><DeclaredValueRequired>true</ DeclaredValueRequired><DueSenderRequired>false</DueSenderRequired></ SpecialService><SpecialService><ServiceID>0</ ServiceID><ServiceName>Certified Mail&lt;sup&gt;&amp;reg;&lt;/sup&gt;</ ServiceName><Available>true</Available><AvailableOnline>false</ AvailableOnline><Price>3.10</Price><PriceOnline>0</PriceOnline></ SpecialService><SpecialService><ServiceID>19</ ServiceID><ServiceName>Adult Signature Required</ ServiceName><Available>false</Available><AvailableOnline>true</ AvailableOnline><Price>0</Price><PriceOnline>4.95</PriceOnline></ SpecialService></SpecialServices></Postage></Package></RateV4Response>

This is my attempt to convert. I thought of setting up a blank array then filling that array with the specialservice arrays

$data = strstr($result, '<?');
// echo '<!-- '. $data. ' -->'; // Uncomment to show XML in comments
$xml_parser = xml_parser_create();
xml_parser_set_option($xml_parser,XML_OPTION_TARGET_ENCODING, "ISO-8859-1");
xml_parse_into_struct($xml_parser, $result, $vals, $index);
xml_parser_free($xml_parser);
$params = array();
$level = array();
foreach ($vals as $xml_elem) {
    if ($xml_elem['type'] == 'open') {
        if (array_key_exists('attributes',$xml_elem)) {
list($level[$xml_elem['level']],$extra) = array_values($xml_elem['attributes']);
        } else {
                $level[$xml_elem['level']] = $xml_elem['tag'];
        }
    }
    if ($xml_elem['type'] == 'complete') {
    $start_level = 1;
    $php_stmt = '$params';
    while($start_level < $xml_elem['level']) {
        $php_stmt .= '[$level['.$start_level.']]';
        $start_level++;
    }
    $php_stmt .= '[$xml_elem[\'tag\']] = $xml_elem[\'value\'];';
                        
    eval($php_stmt);
    }
}

... then trying to pull data from the results of the $php_stmt


$sid = array();
$numserv = count($params['RATEV4RESPONSE'][''.$p.$ack.''][$cId] ['SPECIALSERVICES']);
if($numserv > 0) {
foreach($params['RATEV4RESPONSE'][''.$p.$ack.''][$cId] ['SPECIALSERVICES']['SPECIALSERVICE'] as $sp_servs) {
                $sid_val = $sp_servs['SERVICEID'];
                if(in_array($sid_val, $sid)) {
                        return;
                } else {
                        if($sp_servs['AVAILABLEONLINE'] == true) {
                                $extracost += $sp_servs['PRICEONLINE'];
                        } else {
                                $extracost += $sp_servs['PRICE'];
                        }
                        $sid[$i] = $sid_val;
                }
        }
}

echo("<br><br>Services Array :<br>");
$num_array_items = count($sid);
for($i=0; $i < $num_array_items; $i++) {
        echo($i.". ".$sid[$i]."<br>");
}

Karl DeSaulniers
Design Drumm
http://designdrumm.com


--- End Message ---
--- Begin Message ---

On Feb 25, 2013, at 7:50 PM, Jim Lucas wrote:

On 02/25/2013 05:40 PM, Karl DeSaulniers wrote:
Hi Guys/Gals,
If I have an multidimensional array and it has items that have the same
name in it, how do I get the values of each similar item?

EG:

specialservices => array(
specialservice => array(
serviceid => 1,
servicename=> signature required,
price => $4.95
),
secialservice => array(
serviceid => 15,
servicename => return receipt,
price => $2.30
)
)

How do I get the prices for each? What would be the best way to do this?
Can I utilize the serviceid to do this somehow?
It is always going to be different per specialservice.

TIA,

Best,

Karl DeSaulniers
Design Drumm
http://designdrumm.com



This will never work. Your last array will always overwrite your previous array.

Here is how I would suggest building it:


$items = array(
   1 => array(
       serviceid => 1,
       servicename=> signature required,
       price => $4.95
   ),
   15 => array(
       serviceid => 15,
       servicename => return receipt,
       price => $2.30
   )
)

This will ensure that your first level indexes never overwrite themselves.

But, with that change made, then do this:

foreach ( $items AS $item ) {
 if ( array_key_exists('price', $item) ) {
   echo $item['price'];
 } else {
   echo 'Item does not have a price set';
 }
}

Resources:
http://php.net/foreach
http://php.net/array_key_exists

--
Jim Lucas

http://www.cmsws.com/
http://www.cmsws.com/examples/


Thanks Jim,
However I have no control over how the USPS sends back the response.
See my more detailed email.

Best,

Karl DeSaulniers
Design Drumm
http://designdrumm.com


--- End Message ---
--- Begin Message --- Never mind. I found a different function that reads out the children as well into the array.

                
                function xml_parse_into_assoc($data) {
                          $p = xml_parser_create();
                        
                          xml_parser_set_option($p, XML_OPTION_CASE_FOLDING, 0);
                          xml_parser_set_option($p, XML_OPTION_SKIP_WHITE, 1);
                        
                          xml_parse_into_struct($p, $data, $vals, $index);
                          xml_parser_free($p);
                        
                          $levels = array(null);
                        
                          foreach ($vals as $val) {
                            if ($val['type'] == 'open' || $val['type'] == 
'complete') {
                              if (!array_key_exists($val['level'], $levels)) {
                                $levels[$val['level']] = array();
                              }
                            }
                        
                            $prevLevel =& $levels[$val['level'] - 1];
                            $parent = $prevLevel[sizeof($prevLevel)-1];
                        
                            if ($val['type'] == 'open') {
                              $val['children'] = array();
                              array_push(&$levels[$val['level']], $val);
                              continue;
                            }
                        
                            else if ($val['type'] == 'complete') {
                              $parent['children'][$val['tag']] = $val['value'];
                            }
                        
                            else if ($val['type'] == 'close') {
                              $pop = array_pop($levels[$val['level']]);
                              $tag = $pop['tag'];
                        
                              if ($parent) {
                                if (!array_key_exists($tag, 
$parent['children'])) {
                                  $parent['children'][$tag] = $pop['children'];
                                }
                                else if (is_array($parent['children'][$tag])) {
                                    if(!isset($parent['children'][$tag][0])) {
                                        $oldSingle = $parent['children'][$tag];
                                        $parent['children'][$tag] = null;
                                        $parent['children'][$tag][] = 
$oldSingle;
                        
                                    }
                                      $parent['children'][$tag][] = 
$pop['children'];
                                }
                              }
                              else {
                                return(array($pop['tag'] => $pop['children']));
                              }
                            }
                        
                            $prevLevel[sizeof($prevLevel)-1] = $parent;
                          }
                }


$params = xml_parse_into_assoc($result);//$result = xml result from USPS api

Original function by: jemptymethod at gmail dot com
Duplicate names fix by: Anonymous (comment right above original function)

Best,
Karl


On Feb 25, 2013, at 7:50 PM, Jim Lucas wrote:

On 02/25/2013 05:40 PM, Karl DeSaulniers wrote:
Hi Guys/Gals,
If I have an multidimensional array and it has items that have the same
name in it, how do I get the values of each similar item?

EG:

specialservices => array(
specialservice => array(
serviceid => 1,
servicename=> signature required,
price => $4.95
),
secialservice => array(
serviceid => 15,
servicename => return receipt,
price => $2.30
)
)

How do I get the prices for each? What would be the best way to do this?
Can I utilize the serviceid to do this somehow?
It is always going to be different per specialservice.

TIA,

Best,

Karl DeSaulniers
Design Drumm
http://designdrumm.com



This will never work. Your last array will always overwrite your previous array.

Here is how I would suggest building it:


$items = array(
   1 => array(
       serviceid => 1,
       servicename=> signature required,
       price => $4.95
   ),
   15 => array(
       serviceid => 15,
       servicename => return receipt,
       price => $2.30
   )
)

This will ensure that your first level indexes never overwrite themselves.

But, with that change made, then do this:

foreach ( $items AS $item ) {
 if ( array_key_exists('price', $item) ) {
   echo $item['price'];
 } else {
   echo 'Item does not have a price set';
 }
}

Resources:
http://php.net/foreach
http://php.net/array_key_exists

--
Jim Lucas

http://www.cmsws.com/
http://www.cmsws.com/examples/

Karl DeSaulniers
Design Drumm
http://designdrumm.com


--- End Message ---
--- Begin Message ---
I have the following:

$dsn = "mysqli://$username:$password@$hostname2/$database";
$options = array(
    'debug' => 3,
    'result_buffering' => false,
  );
  $dbh =& MDB2::factory($dsn, $options);
        if (PEAR::isError($mdb2))
        {
                die($mdb2->getMessage());
        }




function tallyCart($_u_id,$dbh){
       while($row = $result->fetchrow(MDB2_FETCHMODE_ASSOC)) {
                $_showCheckOut=1;
$_pdetail=new ProductDetail($row{'product_ID'}, $row{'product_Quantity'}, $_u_id);
                 $_getSubTotal += $_pdetail->_subTotal;
                 $_counter++;
        }
}

I'm getting:  Call to undefined method MDB2_Error::fetchrow()

anyone have any ideas?  Can I not pass a database handle to a function?

Thanks,
Curtis


--- End Message ---

Reply via email to