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

?>

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.