Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

php question (Wordpress)

Options
  • 02-02-2009 5:30pm
    #1
    Registered Users Posts: 7,468 ✭✭✭


    Still new to php so go easy :P

    So what I want to do is add an element to an array. So what I'm doing is using the get_tags() function to return an array (tags) of tag arrays. Each tag has the following structure:

    [php]
    [term_id] => 28
    [name] => Featured
    [slug] => featured
    [term_group] => 0
    [term_taxonomy_id] => 29
    [taxonomy] => post_tag
    [description] =>
    [parent] => 0
    [count] => 6
    [/php]

    What I want to do is iterate through the tags and add a new element to each tag array.

    So for I've tried iterating through and adding the field but it's not saved outside of the foreach loop:
    [php]
    $tags = get_tags();
    foreach($tags as $tag)
    {
    $tag = get_object_vars($tag);
    array_push($tag, 'secondvalue');
    $tag = "hello";
    }

    foreach($tags as $tag)
    {
    $tag = get_object_vars($tag);
    // The element 'secondvalue' isn't present in the next line of code
    echo $tag . " " . $tag . " | ";
    }
    [/php]

    So what am I doing wrong? How do I get the new element to remain in $tags?


Comments

  • Registered Users Posts: 4,769 ✭✭✭cython


    I'm open to correction here, but I think the foreach copies out the element, so you're not actually adding to the original array element there (pass by value vs pass by reference and all that). My guess would be to try something like
    [php]
    $tags = get_tags();
    foreach($tags as $tag_index => $tag)
    {
    $tag = get_object_vars($tag);
    array_push($tag, 'secondvalue');
    $tag = "hello";
    $tags[$tag_index] = $tag;
    }

    foreach($tags as $tag)
    {
    $tag = get_object_vars($tag);
    // The element 'secondvalue' isn't present in the next line of code
    echo $tag . " " . $tag . " | ";
    }
    [/php]

    I haven't tested this, but it should save the updated tag back into the array for you in the same position


  • Registered Users Posts: 7,468 ✭✭✭Evil Phil


    That didn't seem to work for me (I'd say the problem is with me, not your code :)), what I've ended up doing is:

    [php]
    $tags = get_tags();
    reset($tags);
    while(list($tag, $item) = each($tags))
    {
    $item->secondvalue = "hello";
    }
    foreach($tags as $tag)
    {
    $tag = get_object_vars($tag);
    echo $tag . " " . $tag . " | ";
    }
    [/php]

    Works fine.


Advertisement