Simple array lookup - php

I have an array, $persons
When I execute: print_r($persons) I get:
(
[0] => 30131
[1] => 29763
)
The two five-digit numbers are IDs for two posts in a CPT called people
How do I iterate through the array and print the title of each post?
My best guess returns nothing:
foreach( $persons as $person ):
$title = get_the_title( $person->ID );
$peopleout .= $title . ', ' ;
endforeach;
echo $peopleout

Judging from your first snippet, $person inside your loop is a single value, not an object.
That means you should change the $title = lines to this:
$title = get_the_title($person);
Also, you will currently be adding an extra comma at the end of the string. To resolve this, I would add the title to an array, then implode that array to echo the values. That would look like this;
$peopleout = [];
foreach( $persons as $person ):
$peopleout[] = get_the_title($person);
endforeach;
echo implode(", ", $peopleout);

$person is no object, so keep it plain as it contains the ID.
$title = get_the_title($person);
Just for fun you can do all of this as a one-liner.
echo implode(', ', array_map(fn($id) => get_the_title($id), $persons));

Related

php JSON_DECODE for different data length

From mysql, I have a data BLOB data type which has two different scenarios (Please see below). I am trying to put them into a string. Below is the process that I am doing:
1. Query:
$names= $results[0]->name;
print_r($names);
First scenario:
[{"Name":"Mike"},{"Name":"Sean"}]
Second scenario:
{"Name":"Mike Smith","Spaces":"1"}
2. JSON_DECODE
$data = json_decode(stripslashes($names),true);
print_r($data);
First scenario:
Array
(
[0] => Array
(
[Name] => Mike
)
[1] => Array
(
[Name] => Smith
)
)
Second scenario:
Array
(
[Name] => Mike Smith
[Spaces] => 1
)
3. What I am trying to do: To put them into a string
$string = '';
for ($i=0; $i <sizeof($data) ; $i++){
$row = $data[$i];
$name = $row -> Name;
if(isset($row -> Spaces)){
$number = '(' . $row -> Spaces . ')';
}else{
$number = '';
};
$string .= $name . $number . ', ';
};
//Remove last comma
$refined = rtrim($string,', ');
print_r($refined);
4. ISSUE
The issue I am having is that because the data can have two different scenarios like shown in the "1.Query", I can't predict or generalize it and getting errors like "Trying to get property of non-object".
How can I fix this?
Since you're passing true to the $assoc parameter of json_decode, $row->Name will never be the right syntax, since you have an array, and that's syntax for accessing objects; you want $row['Name'] instead. (It's unusual to put space around the -> by the way.)
However, you have basically the right idea on this line:
if(isset($row -> Spaces)){
For an array, that would instead by:
if(isset($row['Spaces'])){
You can do the same thing to see if you've got a name, or a list of names:
if(isset($row['Name'])) {
// In scenario B
echo $row['Name'];
// check for 'Spaces' etc
} else {
// In scenario A
foreach ( $row as $item ) {
echo $item['Name'];
}
}
Note my use of a foreach loop here, which is much neater than your for loop for this kind of thing.
Well I'll edit my answer for better understanding
$str1 = '[{"Name":"Mike"},{"Name":"Sean"}]';
$str2 = '{"Name":"Mike Smith","Spaces":"1"}';
$json1 = json_decode($str1, false);
$json2 = json_decode($str2, false);
if(is_object($json1))
{ echo 'json1 is object<br>'; } else
{ echo 'json1 is NOT object<br>'; }
if(is_object($json2))
{ echo 'json2 is object'; } else
{ echo 'json2 is NOT object'; }
http://php.net/manual/en/function.is-object.php

PHP form array notation, reversed?

So, I have this form that is rather complicated, and the form fields are named to comply with PHP array notation, as such:
<input name='service[123][info]' value=''>
And this of course works as intended and I get the array in $_POST, which I sanitize and then keep in $in. But now I want to reverse-engineer this, when I am iterating over the form again, I have this in $in:
array(
123 => array(
"info" => "foo"
)
)
And when I come to any given form field, I know that the field name is "service[123][info]" but how do I find "foo" in the sent array? Basically, I want to set the value="" parameter in the input when I have data for this field, and the data is kept in the $in array but the only reference to the data I have is the string "service[123][info]". Should I use regexp to parse that string? Sounds inflexible.
Basically, I would like something like:
$name = "service[123][info]";
$value = form_array_lookup($name, $in);
That sets $value to the correct value from $in as referenced by $name. I hope I am making myself clear. Thanks for any comment.
This is a very case-specific (and therefore, not very desirable) example, but the general idea is to use only one delimiter between items, explode the string, and then loop through the result, checking if each item index exists.
function parse_array_path( $string,array $subject ){
// remove ending brackets
$string = str_replace( "]","",$string );
// "[" is now the sole delimiter
$part = explode( "[",$string );
// loop and check for each index in subject array
$i = reset( $part );
do{
if( ! isset( $subject[$i] ) ){
return null;
}
$subject = $subject[$i];
}
while( $i = next( $part ) );
return $subject;
}
example usage:
<?php
$a = array(
"service"=>array(
123=>array(
"info"=>"hello, world"
)
)
);
$s = "service[123][info]";
print parse_array_path( $s,$a ); // "hello, world"
Use a 'foreach' to loop through the array and you can reassign the keys or values in any order you wish.
foreach ($in AS $in_key => $in_val) {
foreach ($in_val AS $in_val_key => $in_val_val) {
// ASSIGN VALUES TO A NEW ARRAY IF YOU WISH
// YOU NOW HAVE $in_key, $in_val_key, $in_val_val
// THAT YOU CAN WORK WITH AND ASSIGN
$array[$in_val_val] = $in_val_key; // OR WHATEVER
}
}

Wordpress and custom fields in a loop

Say I have custom fields with the keys p_title_1 p_value_1 p_title_2 p_value_2
Each of these has values within them and I would like to loop through p_title_[i] and p_value_[i] and show them on the page so that title and value would be grouped together in their own div.
I can't seem to figure out how to write it as a loop to show the 1's together and 2's together.
Reason it needs to be in a loop is incase more custom fields get added in the future. At current I have the following but it only echos the key and value
<?php
$custom_fields = get_post_custom( get_the_ID() );
$my_custom_field = $custom_fields['p_title_1'];
foreach ( $my_custom_field as $key => $value )
echo $key . " => " . $value . "<br />";
?>
Help is appreciated
Use the field name to build an array.
Where the array looks like:
array
1 =>
array
'title' => 'title 1'
'value' => 'value 1'
Loop through your fields and add to the array:
You can get the array index using explode function
$parts = explode ( '_' , $fieldname );
$name = $parts[0];
$index = $parts[1];
And add the value to the array:
$array[$index][$name] = $value;

Using foreach loop through array in an array using php

I am fairly new to PHP and have been working on looping through this array for days...sigh...
http://pastebin.com/Rs6P4e4y
I am trying to get the name and headshot values of the writers and directors array.
I've been trying to figure out the foreach function to use with it, but have had no luck.
<?php foreach ($directors as $key => $value){
//print_r($value);
}
?>
Any help is appreciated.
You looking for some such beast? You didn't write how you wanted to process them, but hopefully this helps you.
$directors = array();
foreach( $object->people->directors as $o )
$directors[] = array( 'name' => $o->name, 'headshot' => $o->images->headshot );
$writers = array();
foreach( $object->people->writers as $o )
$writers[] = array( 'name' => $o->name, 'headshot' => $o->images->headshot );
var_dump( $directors );
var_dump( $writers );
Last note, if there's no guarantee that these members are set, you use isset before any dirty work.
Hope this helps.
Use -> to access properties of the objects.
foreach ($directors as $director) {
echo 'Name: ' . $director->name . "\n";
echo "Headshot: " . $director->images->headshot . "\n";
}
Your solution has already been posted, but I want to add something:
This isn't an Array, it's an object. Actually the directors property of the object is an Array. Look up what an object is and what associative arrays are!
Objects have properties, arrays have keys and values.
$object = new stdClass();
$object->something = 'this is an object property';
$array = new array();
$array['something'] = 'this is an array key named something';
$object->arrayproperty = $array;
echo $object->arrayproperty['something']; //this is an array key named something
Good luck with learning PHP! :)
Having variable $foo, which is an object, you can access property bar using syntax:
$foo->bar
So if you have an array od directors named $directors, you can simply use it the same way in foreach:
foreach ($directors as $value){
echo $value->name." ".$value->images->headshot;
}

PHP - how to remove data using PHP

How can I remove ?cat= from the example 1 so it can look like example 2 using PHP.
Example 1
?cat=some-cat
Example 2
some-cat
Easy, use str_replace:
$cat = '?cat=some-cat';
$cat = str_replace('?cat=', '', $cat);
EDIT:
If you are pulling this query string through something like $_SERVER['QUERY_STRING'], then I'd opt for you to use $_GET, which is an associative array of the GET variables passed to your script, so if your query string looked like this:
?cat=some-cat&dog=some-dog
The $_GET array would look like this:
(
'cat' => 'some-cat',
'dog' => 'some-dog'
)
$cat = $_GET['cat']; //some-cat
$dog = $_GET['dog']; //some-dog
Another edit:
Say you had an associative array of query vars you wish to append onto a URL string, you'd do something like this:
$query_vars = array();
$query_vars['cat'] = 'some-cat';
$query_vars['dog'] = 'some-dog';
foreach($query_vars as $key => $value) {
$query_vars[] = $key . '=' . $value;
unset($query_vars[$key]);
}
$query_string = '?' . implode('&', $query_vars); //?cat=some-cat&dog=some-dog
Yes, you can, very easily:
$cat = '?cat=some-cat';
$cat = substr($cat, 5); // remove the first 5 characters of $cat
This may not be the best way to do this. That will depend on what you are attempting to achieve...

Categories