Jump to content

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?
Link to comment
https://forums.phpfreaks.com/topic/20412-does-this-array-function-exist/
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
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]
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]
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!
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!
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.