Jump to content

Looping through Array of Associative Arrays


danielj

Recommended Posts

I'm having trouble looping through an array. I admit that I'm not that great with associative arrays. The print_r line in my code below prints the array that I am trying to use. It looks like it is an array of associative arrays.

 

Here is a small part of the output.

 

  • [*]Array ( [0] => WP_Post Object ( [iD] => 52711 [post_author] => 31 [post_date] => 2014-06-05 15:19:12 [post_date_gmt] => 2014-06-05 19:19:12 [post_content] => Test [post_title] => Test [post_excerpt] => [post_status] => publish [comment_status] => open [ping_status] => open [post_password] => [post_name] => test

 

Here is the code.

	$att = shortcode_atts ( array('category' => 'news', 'posts_per_page' => '0', 'orderby' => 'post_date'), $args);		$posts_array = get_posts($att);	print_r(array_values($posts_array));	echo "<ul>";	foreach ($posts_array as $key => $value){		foreach($value as $key2 => $value2){			echo "<li>";				echo $value2["post_name"];			echo "</li>";		}	}  	echo "</ul>";

The output doesn't make sense to me. It is a bunch of li items of one character. A few of the li items are: 3 2 2 T T p o o t 2 2 h p 0. Note that each character is a different li item.

 

Thanks for any suggestions.

Link to comment
Share on other sites

That's not a multidimensional array, that's an array of WP_Post objects. It's still letting you loop through the properties of the object like an array though. The characters you are seeing is because you are trying to treat each string property value as an array. $value2 is a string (or number), not an array. You can access string characters using array syntax, for example $str[0] would print the first character of a string. When you access $value2['post_name'] it converts 'post_name' to a number, which is 0, and outputs the first character of each property value. You can see that in your example output. 3 is the first character of the post_author value, the 2s are the first characters of post_date and post_date_gmt, the Ts are from post_content and post_title, etc.

Link to comment
Share on other sites

You are using a wordpress built in function, I know alittle about wordpress output and i guess you left it null

 

Something like this:

  • ARRAY_A - Returns an associative array of field names to values
  • ARRAY_N - returns a numeric array of field values

like

print_r(get_post(7, ARRAY_A));

will return associative array :)

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...