Jump to content

help in how to cut down on repeat code...


blackhawk

Recommended Posts

I came up with the following code to find specific key value pairs from a large array called $order->products...

 

/*Used to get the key value pair in array*/

function seekKey($array, $key, $value)
{
    $ret = array();
    for ($i=0;$i<count($array);$i++)
    {
        if ($array[$i][$key]==$value)
            $ret[] = $array[$i];
    }
    return $ret;
}


/*Set each company as a vendor_id found in $order->products */
$ford = seekKey($order->products, 'vendors_id', '1');
$bmw = seekKey($order->products, 'vendors_id', '2');
$jeep = seekKey($order->products, 'vendors_id', '3');

if (isset($ford[0]['vendors_id'])){
   print $ford . $samething;
}

if (isset($bmw[0]['vendors_id'])){
      print $bmw .  $samething;
}

if (isset($jeep[0]['vendors_id'])){
      print $jeep .  $samething;
}

 

this is fine for me if its only bmw, jeep and poniac.  but anyone know of a way to cut down on this code if i had 27 companies instead of just 3? I just don't want to write 27 if conditions that only changes the company name variable inside each one.  :shrug:

 

thanks for the help!  ;)

 

 

 

Link to comment
https://forums.phpfreaks.com/topic/187276-help-in-how-to-cut-down-on-repeat-code/
Share on other sites

This should work to create variables using the company names, just add to the $company array as many option as you need

 

<?php

/*Used to get the key value pair in array*/

function seekKey($array, $key, $value)
{
    $ret = array();
    for ($i=0;$i<count($array);$i++)
    {
        if ($array[$i][$key]==$value)
            $ret[] = $array[$i];
    }
    return $ret;
}

/*Set each company as a vendor_id found in $order->products */
$companies = array(1 => 'ford', 2 => 'bmw', 3 => 'jeep');

foreach ($companies as $key => $company)
{
    $$company = array(0=>array('vendors_id'=>'asd')); seekKey($order->products, 'vendors_id', $key);
    if (isset(${$company}[0]['vendors_id'])){
        print ${$company} . $samething;
    }
}

?>

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.