Jump to content

Archived

This topic is now archived and is closed to further replies.

roopurt18

Does this array function exist?

Recommended Posts

I have an array:
[code]
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
        )
)
[/code]

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

Writing such a function is trivial, but why re-invent the wheel?

Share this post


Link to post
Share on other sites
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:
[code]
<?php
function getArray($arr, $key) {
  $res = array();
  foreach ($arr as $sub) $res[] = $sub[$key];
  return $res;
}

$NewArr = getArray($OldArr, 'Trade');
?>
[/code]

hope this helps

Share this post


Link to post
Share on other sites
You wouldn't need to assume anything about the array if you program carefully.

A safer function, IMO:
[code]
<?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;
  }
?>
[/code]

Share this post


Link to post
Share on other sites
Roopurt, Thats a very long-winded way of writing

$newarray = array_values ($arr);

Share this post


Link to post
Share on other sites
[quote author=Barand link=topic=107669.msg432237#msg432237 date=1158003452]
Roopurt, Thats a very long-winded way of writing

$newarray = array_values ($arr);
[/quote]

I don't think they do the same thing.  ^_^

Share this post


Link to post
Share on other sites
[code]$b = ArrayFromArrayByKey($arr, 'Trade');
$c = array_values ($arr);[/code]

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

Share this post


Link to post
Share on other sites
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.

[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;
        }
      }
    }
    return $Ret;
  }

?>
[/code]
gave this output
[code]
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
        )

)
[/code]

[b]The fixed code:[/b]
[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;
  }
?>
[/code]
gives:
[code]
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
        )

)
[/code]

Share this post


Link to post
Share on other sites
$Ret[] = $val[color=red][$key][/color];

I see you you spotted the error in your "careful coding" ;)

Share this post


Link to post
Share on other sites
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!

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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!

Share this post


Link to post
Share on other sites

×

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.