Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Aug 2007
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Question Extracing keys and values from associative arrays

    I have the following 2 dimensional array

    PHP Code:
    $links = array(array('a1' => 'a1.php','a2' => 'a2.php','a3' => 'a3.php'),
                      array(
    'b1' => 'b1.php','b2' => 'b2.php','b3' => 'b3.php'), 
                      array(
    'c1' => 'c1.php','c2' => 'c2.php','c3' => 'c3.php'),
                      array(
    'd1' => 'd1.php','d2' => 'd2.php','d3' => 'd3.php')
                       ); 
    I would like to extract the first keys and values form each sub array, to get the following. (don't know how many sub arrays, or their length in advance)
    PHP Code:
    $firstLinks = array('a1' => 'a1.php','b1' => 'b1.php','c1' => 'c1.php','d1' => 'd1.php'), 
    I am struggling to find a simple solution. Can anyone assist?

  • #2
    Banned
    Join Date
    Apr 2007
    Posts
    428
    Thanks
    29
    Thanked 5 Times in 5 Posts
    I can't see a proper "simple" way, but this is how i played with it.. Almost made it, but..

    PHP Code:
    <?php

    $links 
    = array(

                    array(
    'a1' => 'a1.php','a2' => 'a2.php','a3' => 'a3.php'),
                      array(
    'b1' => 'b1.php','b2' => 'b2.php','b3' => 'b3.php'), 
                      array(
    'c1' => 'c1.php','c2' => 'c2.php','c3' => 'c3.php'),
                      array(
    'd1' => 'd1.php','d2' => 'd2.php','d3' => 'd3.php')
    );  


    $firstLinks = array();

    for (
    $i 0$i count($links); $i++) {

        
    $vals = (array_values($links[$i]));

        
    $keys = (array_keys($links[$i]));

        
    $Links = array ($vals[0] => $keys[0]);
        
        
    array_push ($firstLinks$Links);

    }
    print_r ($firstLinks);

    ?>

  • #3
    Super Moderator Inigoesdr's Avatar
    Join Date
    Mar 2007
    Location
    Florida, USA
    Posts
    3,647
    Thanks
    2
    Thanked 406 Times in 398 Posts
    PHP Code:
    $links = array(array('a1' => 'a1.php','a2' => 'a2.php','a3' => 'a3.php'),
                      array(
    'b1' => 'b1.php','b2' => 'b2.php','b3' => 'b3.php'), 
                      array(
    'c1' => 'c1.php','c2' => 'c2.php','c3' => 'c3.php'),
                      array(
    'd1' => 'd1.php','d2' => 'd2.php','d3' => 'd3.php')
                       );  

    $firstLinks = array();
    foreach(
    $links as $k)
    {
        
    $v array_slice($k011);
        
    $firstLinks[key($v)] = $v[key($v)];


  • Users who have thanked Inigoesdr for this post:

    matak (08-23-2007)


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •