How do I return the cat_name value instead of array with PHP?
I did some digging and I understand that the array means there are multiple values coming back from my query. From another post I found print_r so I could see the values. How do I return one of the values though?
This:
<?php
$category = get_the_category();
$parent = get_cat_name($category[0]->category_parent);
$cat_name = get_the_category($category[cat_name]);
echo 'category' . $category . '<br />';
echo 'parent: ' . $parent . '<br />';
echo 'Cat Name: ' . $cat_name . '<br />';
print_r ($cat_name);
?>
Returns this:
categoryArray
parent: Location
Cat Name: Array
Array (
[0] => stdClass Object (
[term_id] => 11
[name] => 开发者_运维问答nashville
[slug] => nashville
[term_group] => 0
[term_taxonomy_id] => 11
[taxonomy] => category
[description] =>
[parent] => 8
[count] => 1
[object_id] => 20
[cat_ID] => 11
[category_count] => 1
[category_description] =>
[cat_name] => nashville
[category_nicename] => nashville
[category_parent] => 8
)
)
How do I make $cat_name return nashville? cat_name = nashville according to the print_r function. This is a wordpress site if that makes a difference, but I am guessing this is a simple coding question.
You're actually dealing with an object there, which is the first element in an array.
Note it says Array ( [0] => stdClass Object (
Use the square brace syntax to access array members
$array_name['key_name']
And the arrow for objects properties
$object->property_name
So in this case,
$category[0]->cat_name
is 'nashville'.
I hope this helps, it looks like you're just asking how to access the value from an array, correct me if I'm wrong. But to get the cat_name from your category array, the syntax would be;
$category['cat_name'];
With this you can access the value.
echo $category['cat_name'];
Should print it to the screen.
精彩评论