Jump to content


Photo

Does this array function exist?


  • Please log in to reply
10 replies to this topic

#1 roopurt18

roopurt18
  • Staff Alumni
  • Advanced Member
  • 3,749 posts
  • LocationCalifornia, southern

Posted 11 September 2006 - 06:09 PM

I have an array:
Array
(
    [72] => Array
        (
            [Trade] => CAB130
            [tdesc] => CABINETRY
        )

    [73] => Array
        (
            [Trade] => CON160
            [tdesc] => CONCRETE - SLAB 1ST DRAW
        )

    [74] => Array
        (
            [Trade] => CON162
            [tdesc] => CONCRETE - SLAB 2ND DRAW
        )

    [75] => Array
        (
            [Trade] => CON168
            [tdesc] => CONCRETE-POST TENSION INSPECTION
        )
)

Is there an existing php function that given that array will return an array from a specific index?
// Return an array of values from $OldArr using key 'Trade'
$NewArr = Func($OldArr, 'Trade');

Writing such a function is trivial, but why re-invent the wheel?
PHP Forms : Part I | Part II

JavaScript: Singleton

http://www.rbredlau.com

#2 obsidian

obsidian
  • Staff Alumni
  • Advanced Member
  • 3,202 posts
  • LocationSeattle, WA

Posted 11 September 2006 - 06:20 PM

i don't believe so, since you'd have to be working with a function that automatically assumes it is only a 2D array, which could be a very dangerous assumption. you could very easily write a function to do that, though:
<?php
function getArray($arr, $key) {
  $res = array();
  foreach ($arr as $sub) $res[] = $sub[$key];
  return $res;
}

$NewArr = getArray($OldArr, 'Trade');
?>

hope this helps
You can't win, you can't lose, you can't break even... you can't even get out of the game.

<?php
while (count($life->getQuestions()) > 0)
{   $life->study(); } ?>
  LINKS: PHP: Manual MySQL: Manual PostgreSQL: Manual (X)HTML: Validate It! CSS: A List Apart | IE bug fixes | Zen Garden | Validate It! JavaScript: Reference Cards RegEx: Everything RegEx

#3 roopurt18

roopurt18
  • Staff Alumni
  • Advanced Member
  • 3,749 posts
  • LocationCalifornia, southern

Posted 11 September 2006 - 07:06 PM

You wouldn't need to assume anything about the array if you program carefully.

A safer function, IMO:
<?php
  // ArrayFromArrayByKey
  // $arr - The original array
  // $key - the key we are looking for
  // RETURN:  An array of values
  // For each element in $arr, look for the key $key and add it's value
  // to our return array
  function ArrayFromArrayByKey($arr, $key){
    $Ret = Array();
    if(is_array($arr) && count($arr)){
      foreach($arr as $val){
        if(is_array($val) && isset($val[$key])){
          $Ret[] = $val;
        }
      }
    }
    return $Ret;
  }
?>

PHP Forms : Part I | Part II

JavaScript: Singleton

http://www.rbredlau.com

#4 Barand

Barand
  • Moderators
  • Sen . ( ile || sei )
  • 18,021 posts

Posted 11 September 2006 - 07:37 PM

Roopurt, Thats a very long-winded way of writing

$newarray = array_values ($arr);
If you are still using mysql_ functions, STOP! Use mysqli_ or PDO. The longer you leave it the more you will have to rewrite.

Donations gratefully received






moon.png

|baaGrid| easy data tables - and more
|baaChart| easy line, column and pie charts

#5 roopurt18

roopurt18
  • Staff Alumni
  • Advanced Member
  • 3,749 posts
  • LocationCalifornia, southern

Posted 11 September 2006 - 07:50 PM

Roopurt, Thats a very long-winded way of writing

$newarray = array_values ($arr);


I don't think they do the same thing.  ^_^
PHP Forms : Part I | Part II

JavaScript: Singleton

http://www.rbredlau.com

#6 Barand

Barand
  • Moderators
  • Sen . ( ile || sei )
  • 18,021 posts

Posted 11 September 2006 - 07:54 PM

$b = ArrayFromArrayByKey($arr, 'Trade');
$c = array_values ($arr);

then compare $b and $c
echo '<pre>', print_r($b, true), '</pre>';
echo '<pre>', print_r($c, true), '</pre>';

If you are still using mysql_ functions, STOP! Use mysqli_ or PDO. The longer you leave it the more you will have to rewrite.

Donations gratefully received






moon.png

|baaGrid| easy data tables - and more
|baaChart| easy line, column and pie charts

#7 roopurt18

roopurt18
  • Staff Alumni
  • Advanced Member
  • 3,749 posts
  • LocationCalifornia, southern

Posted 11 September 2006 - 08:16 PM

Well, we were both wrong.  I made a silly typo.  In the case of the array of arrays, it did behave the same as array_values.  With other inputs they behaved differently.

<?php
  define('NL', "\n");

  $Out = '';
  $A = array( "hello", "world", "how", "are", "you" );
  $B = array( "key1" => "i", "key2" => "am", "key3" => "fine" );
  $C = array( array( "key1" => "row1_val1", "key2" => "row1_val2" ),
              array( "key1" => "row2_val1", "key2" => "row2_val2" ),
              array( "key1" => "row3_val1", "key2" => "row3_val2" ),
              array( "key1" => "row4_val1", "key2" => "row4_val2" ),
              array( "key1" => "row5_val1", "key2" => "row5_val2" )
            );

  $Out .= 'ArrayFromArrayByKey($A, \'Key\'):' . NL
        . print_r(ArrayFromArrayByKey($A, 'Key'), true) . NL;
  $Out .= 'array_values($A):' . NL
        . print_r(array_values($A), true) . NL;

  $Out .= 'ArrayFromArrayByKey($B, \'key2\'):' . NL
        . print_r(ArrayFromArrayByKey($B, 'key2'), true) . NL;
  $Out .= 'array_values($B):' . NL
        . print_r(array_values($B), true) . NL;

  $Out .= 'ArrayFromArrayByKey($C, \'key2\'):' . NL
        . print_r(ArrayFromArrayByKey($C, 'key2'), true) . NL;
  $Out .= 'array_values($C):' . NL
        . print_r(array_values($C), true) . NL;

  echo '<pre style="text-align: left;">' . $Out . '</pre>';

  // ArrayFromArrayByKey
  // $arr - The original array
  // $key - the key we are looking for
  // RETURN:  An array of values
  // For each element in $arr, look for the key $key and add it's value
  // to our return array
  function ArrayFromArrayByKey($arr, $key){
    $Ret = Array();
    if(is_array($arr) && count($arr)){
      foreach($arr as $val){
        if(is_array($val) && isset($val[$key])){
          $Ret[] = $val;
        }
      }
    }
    return $Ret;
  }

?>
gave this output
ArrayFromArrayByKey($A, 'Key'):
Array
(
)

array_values($A):
Array
(
    [0] => hello
    [1] => world
    [2] => how
    [3] => are
    [4] => you
)

ArrayFromArrayByKey($B, 'key2'):
Array
(
)

array_values($B):
Array
(
    [0] => i
    [1] => am
    [2] => fine
)

ArrayFromArrayByKey($C, 'key2'):
Array
(
    [0] => Array
        (
            [key1] => row1_val1
            [key2] => row1_val2
        )

    [1] => Array
        (
            [key1] => row2_val1
            [key2] => row2_val2
        )

    [2] => Array
        (
            [key1] => row3_val1
            [key2] => row3_val2
        )

    [3] => Array
        (
            [key1] => row4_val1
            [key2] => row4_val2
        )

    [4] => Array
        (
            [key1] => row5_val1
            [key2] => row5_val2
        )

)

array_values($C):
Array
(
    [0] => Array
        (
            [key1] => row1_val1
            [key2] => row1_val2
        )

    [1] => Array
        (
            [key1] => row2_val1
            [key2] => row2_val2
        )

    [2] => Array
        (
            [key1] => row3_val1
            [key2] => row3_val2
        )

    [3] => Array
        (
            [key1] => row4_val1
            [key2] => row4_val2
        )

    [4] => Array
        (
            [key1] => row5_val1
            [key2] => row5_val2
        )

)

The fixed code:
<?php
  define('NL', "\n");

  $Out = '';
  $A = array( "hello", "world", "how", "are", "you" );
  $B = array( "key1" => "i", "key2" => "am", "key3" => "fine" );
  $C = array( array( "key1" => "row1_val1", "key2" => "row1_val2" ),
              array( "key1" => "row2_val1", "key2" => "row2_val2" ),
              array( "key1" => "row3_val1", "key2" => "row3_val2" ),
              array( "key1" => "row4_val1", "key2" => "row4_val2" ),
              array( "key1" => "row5_val1", "key2" => "row5_val2" )
            );

  $Out .= 'ArrayFromArrayByKey($A, \'Key\'):' . NL
        . print_r(ArrayFromArrayByKey($A, 'Key'), true) . NL;
  $Out .= 'array_values($A):' . NL
        . print_r(array_values($A), true) . NL;

  $Out .= 'ArrayFromArrayByKey($B, \'key2\'):' . NL
        . print_r(ArrayFromArrayByKey($B, 'key2'), true) . NL;
  $Out .= 'array_values($B):' . NL
        . print_r(array_values($B), true) . NL;

  $Out .= 'ArrayFromArrayByKey($C, \'key2\'):' . NL
        . print_r(ArrayFromArrayByKey($C, 'key2'), true) . NL;
  $Out .= 'array_values($C):' . NL
        . print_r(array_values($C), true) . NL;

  echo '<pre style="text-align: left;">' . $Out . '</pre>';

  // ArrayFromArrayByKey
  // $arr - The original array
  // $key - the key we are looking for
  // RETURN:  An array of values
  // For each element in $arr, look for the key $key and add it's value
  // to our return array
  function ArrayFromArrayByKey($arr, $key){
    $Ret = Array();
    if(is_array($arr) && count($arr)){
      foreach($arr as $val){
        if(is_array($val) && isset($val[$key])){
          $Ret[] = $val[$key];
        }
      }
    }
    return $Ret;
  }
?>
gives:
ArrayFromArrayByKey($A, 'Key'):
Array
(
)

array_values($A):
Array
(
    [0] => hello
    [1] => world
    [2] => how
    [3] => are
    [4] => you
)

ArrayFromArrayByKey($B, 'key2'):
Array
(
)

array_values($B):
Array
(
    [0] => i
    [1] => am
    [2] => fine
)

ArrayFromArrayByKey($C, 'key2'):
Array
(
    [0] => row1_val2
    [1] => row2_val2
    [2] => row3_val2
    [3] => row4_val2
    [4] => row5_val2
)

array_values($C):
Array
(
    [0] => Array
        (
            [key1] => row1_val1
            [key2] => row1_val2
        )

    [1] => Array
        (
            [key1] => row2_val1
            [key2] => row2_val2
        )

    [2] => Array
        (
            [key1] => row3_val1
            [key2] => row3_val2
        )

    [3] => Array
        (
            [key1] => row4_val1
            [key2] => row4_val2
        )

    [4] => Array
        (
            [key1] => row5_val1
            [key2] => row5_val2
        )

)

PHP Forms : Part I | Part II

JavaScript: Singleton

http://www.rbredlau.com

#8 Barand

Barand
  • Moderators
  • Sen . ( ile || sei )
  • 18,021 posts

Posted 11 September 2006 - 08:22 PM

$Ret[] = $val[$key];

I see you you spotted the error in your "careful coding" ;)
If you are still using mysql_ functions, STOP! Use mysqli_ or PDO. The longer you leave it the more you will have to rewrite.

Donations gratefully received






moon.png

|baaGrid| easy data tables - and more
|baaChart| easy line, column and pie charts

#9 roopurt18

roopurt18
  • Staff Alumni
  • Advanced Member
  • 3,749 posts
  • LocationCalifornia, southern

Posted 11 September 2006 - 08:28 PM

Heh, logical errors happen.  I still consider my coding more careful than Joe Schmoe's and overall more reliable.  If I were actually using that function I would have found the bug in a couple moments and fixed it then.

But careful eye you have, Sir!
PHP Forms : Part I | Part II

JavaScript: Singleton

http://www.rbredlau.com

#10 Barand

Barand
  • Moderators
  • Sen . ( ile || sei )
  • 18,021 posts

Posted 11 September 2006 - 08:44 PM

Sorry about that, but having set yourself up by "lecturing" on careful coding I couldn't believe you hadn't tested it too. Couldn't resist the dig ;D
If you are still using mysql_ functions, STOP! Use mysqli_ or PDO. The longer you leave it the more you will have to rewrite.

Donations gratefully received






moon.png

|baaGrid| easy data tables - and more
|baaChart| easy line, column and pie charts

#11 roopurt18

roopurt18
  • Staff Alumni
  • Advanced Member
  • 3,749 posts
  • LocationCalifornia, southern

Posted 11 September 2006 - 10:13 PM

Point taken!  But honestly I just try to set good coding examples for the beginners perusing these forums.  There's a lot of instances where data validation and testing will save a ton of headache.  Also, you never know when you'll have to go through and fix someone else's horrible, broken code.  As that's part of my current job, I'd like to save anyone else the trouble of having to do it if I can.

Cheers!
PHP Forms : Part I | Part II

JavaScript: Singleton

http://www.rbredlau.com




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users