PHP, file_get_contents, for loop, str_replace - php

I am quite new with PHP and I am trying to read something form an API.
At the moment I use
$homepage = file_get_contents('http://www.site.com');
echo $homepage
This returns something which looks like this:
Array
(
[0] => Array
(
[name] => myname
[user_id] => 31232
)
[1] => Array
(
[name] => anothername
[user_id] => 23534
)
)
So here is what I want: I only want to read the [name] => x and leave the rest, so I tried a for loop within str_replace, but all I got were errors.
I hope someone is able to help me
Edit:
I just saw I could set is as a json text too, it returns something like
[{"name":"myname","user_id":"31232"},{"name":"anothername","user_id":"23534"}]
Edit2: Thank you Tuga, that was exactly what I was searching for :) I can't upvote, since my reputaion is below 15, is there another way for me to show your answer helped?

$array = json_decode($homepage); will return an array, then you can loop the array containing objects and use 'name' attribute :
foreach ($array as $obj) echo $obj->name;

Related

PHP arrays within an array - nested arrays PHP

I'm using ACF Pro plugin for Wordpress and use repeater fields.
With this code I get all the field values and additional info in an array:
$fields = get_field_object('slideshow');
With this code I can narrow it down to what I want to achieve:
print_r($fields[value];
By now I get this array below:
Array
(
[0] => Array
(
[videoWebm] => /wc/data/uploads/sea.webm
[videoMp4] => /wc/data/uploads/sea1.mp4
[text] => Test1
[kund] => Kund1
[link1] =>
[link2] =>
)
[1] => Array
(
[videoWebm] => /wc/data/uploads/turntable.webm
[videoMp4] => /wc/data/uploads/turntable.mp4
[text] => Test2
[kund] => Kund2
[link1] =>
[link2] =>
)
)
it can grow more - like [2] => Array, [3] => Array etc.
I want to access all videoWebm & videoMp4 values.
As of now I know how to access a specific value - for example:
print_r($fields[value][0][videoWebm]);
But I can't figure out how to access all of them and put them in two new arrays. One for videoWebm values and one for videoMp4 values. The problem for me is the index value when I try to loop thru the array. I don't know if this really is the way to go...
Anyone suggestions?
Best, Niklas
You can use foreach:
foreach ($fields[value] as $field) {
$videoWebms[] = $field['videoWebm']
$videoMp4s[] = $field['videoMp4'];
}
Or as splash58 said, use array_column:
$vieoWebms = array_column($fields[value], 'videoWebm');
$vieoMp4s = array_column($fields[value], 'videoMp4');
I would highly recommend you learn about php's foreach, it is very powerful and widely used (maybe a little too widely).
https://www.google.com/search?q=php%20foreach
To get the value from repeater use this :
$slides = get_field('slideshow');
if($slides){
foreach($slides as $slide){
echo $slide['videoWebm'];
echo $slide['text'];
echo $slide['kund]'];
echo $slide['link1'];
echo $slide['link2'];
}
}

How to change variable names inside array php

Ok so I have been struggling with this for hours now and I cannot seem to figure out what I'm trying to do. I have an array with many percent values placed inside and I'm printing out the first 5 of them. The $percent variables are acquired through similar_text
$array=array($percent12, $percent13, $percent14,
$percent15, $percent16, $percent17,
$percent18, $percent19, $percent110,
$percent111, $percent112, $percent113,
$percent114, $percent115, $percent116,
$percent117, $percent118, $percent119,
$percent120);
print_r(array_slice($array,0,5));
and it outputs like this:
Array ( [0] => 36.015505697169 [1] => 2.4181626187962 [2] => 2.4181626187962 [3] => 5.2153134902083 [4] => 100 )
So what i'm trying to figure out here is if it's possible to print the results of my array as they are listed above. example output would look like this:
Array ( [percent12] => 36.015505697169 [percent13] => 2.4181626187962 [percent14] => 2.4181626187962 [percent15] => 5.2153134902083 [percent16] => 100 )
i feel like this isn't possible, but if not, is there a way to assign the
[0]=> 36.015505697169 [1]=> 2.4181626187962
...etc to output something else say like:
[web0]=> 36.015505697169 [web1] => 2.4181626187962
Please help!! It's driving me crazy!!
You need to make it an associative array:
$array=array('percent12' => $percent12,
'percent13' => $percent13,
...);
I recommend using array_combine()
Basically you're just going to setup your new array with the keys, and pass in your current array for the values, thus creating a new array with the keys you want in the right place.
Try like
$myArr = array_slice($array,0,5);
$i = 0;
foreach($myArr as $key => $value) {
$newArr['web'.$i++] = $value;
}
print_r($newArr);

php convert a string into multi dimensional array

I have seen many posts on here about converting a multi dimensional array into a string but not the other way around so I have a question to ask. I have got the following string of data which is retrieved from a JQuery array via a post:
["enquiry#gardengamesltd.co.uk, sales#gardengamesltd.co.uk","http://www.gardengamesltd.co.uk/acatalog/contactus.html"],["enquiry#gardengames.com","http://www.gardengames.com/contact/"],["info#gardengamesandleisure.com","http://www.gardengamesandleisure.com/ContactUs.aspx"],["playtime#kentgardengameshire.com","http://www.kentgardengameshire.com/contact-us.html"],["sales#gardengamesuk.com","http://www.gardengamesuk.com/contact.php"],["team#gardenknightgames.com","http://www.gardenknightgames.com/contact/"],["ajax-loader#2x.gif","http://www.just-garden-games.co.uk/"]
What I am wanting to do is convert it into an array which looks like so:
Array
(
[0] => Array
(
[Email] => enquiry#gardengamesltd.co.uk, sales#gardengamesltd.co.uk
[FB] => http://www.gardengamesltd.co.uk/acatalog/contactus.html
)
[1] => Array
(
[Email] => enquiry#gardengames.com
[FB] => http://www.gardengames.com/contact/
)
[2] => Array
(
[Email] => info#aaeventhire.com
[FB] => http://www.aaeventhire.com/pricing/garden-games
)
)
I realize I could use $array = explode('","', $harvest_data); however this is only going to give me a single level array and ideally I am wanting to keep email, fb inside an inner array.
Has anyone got any ideas on how I can go about doing this?
Thanks.
As it is, your string is not valid JSON. Wrapping it in a pair of []'s would work in this case so if the input always has this form, this would work:
$json_string = '[' . $your_string . ']';
$your_array = json_decode($json_string);
However, it would be best to make sure that your front-end / javascript posts valid JSON to begin with.
Working example.

PHP - Remove items from an array with given parameter

I've searched around and I found some similar questions asked, but none that really help me (as my PHP abilities aren't quite enough to figure it out). I'm thinking that my question will be simple enough to answer, as the similar questions I found were solved with one or two lines of code. So, here goes!
I have a bit of code that searches the contents of a given directory, and provides the files in an array. This specific directory only has .JPG image files named like this:
Shot01.jpg
Shot01_tn.jpg
so on and so forth. My array gives me the file names in a way where I can use the results directly in an tag to be displayed on a site I'm building. However, I'm having a little trouble as I want to limit my array to not return items if they contain "_tn", so I can use the thumbnail that links to the full size image. I had thought about just not having thumbnails and resizing the images to make the PHP easier for me to do, but that feels like giving up to me. So, does anyone know how I can do this? Here's the code that I have currently:
$path = 'featured/';
$newest = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS));
$array = iterator_to_array($newest);
foreach($array as $fileObject):
$filelist = str_replace("_tn", "", $fileObject->getPathname());
echo $filelist . "<br>";
endforeach;
I attempted to use a str_replace(), but I now realize that I was completely wrong. This returns my array like this:
Array
(
[0] => featured/Shot01.jpg
[1] => featured/Shot01.jpg
[2] => featured/Shot02.jpg
[3] => featured/Shot02.jpg
[4] => featured/Shot03.jpg
[5] => featured/Shot03.jpg
)
I only have 3 images (with thumbnails) currently, but I will have more, so I'm also going to want to limit the results from the array to be a random 3 results. But, if that's too much to ask, I can figure that part out on my own I believe.
So there's no confusion, I want to completely remove the items from the array if they contain "_tn", so my array would look something like this:
Array
(
[0] => featured/Shot01.jpg
[2] => featured/Shot02.jpg
[4] => featured/Shot03.jpg
)
Thanks to anyone who can help!
<?php
function filtertn($var)
{
return(!strpos($var,'_tn'));
}
$array = Array(
[0] => featured/Shot01.jpg
[1] => featured/Shot01_tn.jpg
[2] => featured/Shot02.jpg
[3] => featured/Shot02_tn.jpg
[4] => featured/Shot03.jpg
[5] => featured/Shot03_tn.jpg
);
$filesarray=array_filter($array, "filtertn");
print_r($filesarray);
?>
Just use stripos() function to check if filename contains _tn string. If not, add to array.
Use this
<?php
$array = Array(
[0] => featured/Shot01.jpg
[1] => featured/Shot01_tn.jpg
[2] => featured/Shot02.jpg
[3] => featured/Shot02_tn.jpg
[4] => featured/Shot03.jpg
[5] => featured/Shot03_tn.jpg
)
foreach($array as $k=>$filename):
if(strpos($filename,"_tn")){
unset($array[$k]);
}
endforeach;
Prnt_r($array);
//OutPut will be you new array removed all name related _tn files
$array = Array(
[0] => featured/Shot01.jpg
[2] => featured/Shot02.jpg
[4] => featured/Shot03.jpg
)
?>
I can't understand what is the problem? Is it required to add "_tn" to array? Just check "_tn" existence and don't add this element to result array.
Try strpos() to know if filename contains string "_tn" or not.. if not then add filename to array
$path = 'featured/';
$newest = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS));
$array = iterator_to_array($newest);
$filesarray = array();
foreach($array as $fileObject):
// Check - string contains "_tn" substring or not
if(!strpos($fileObject->getPathname(), "_tn")){
// Check - value already exists in array or not
if(!in_array($fileObject->getPathname(), $filesarray)){
$filesarray[] = $fileObject->getPathname();
}
}
endforeach;
print_r($filesarray);

PHP - search for a key value and then find the value of another key in the same object subarray

I've searched a lot for this, and found several similar questions, but none quite address what I'm trying to accomplish.
I'm trying to write a code that will search a PHP (multi)multidimensional array to see which subarray contains the unique key value that I have. Then I would like it to return the value of a different key in that same object subarray.
$Arraytosearch = Array(
.
//various other subarrays
.
[fields] => Array (
.
.
.
//I don't know the number of the object subarray
[x] => PodioTextItemField Object (
[__attributes] => Array (
[field_id] => 37325091
[type] => text
[external_id] => id
[label] => ID
[values] => Array (
[0] => Array (
[value] => REF100019 ) )
[config] => Array (
[description] => [settings] => Array (
[size] => small )
[required] => [mapping] => [label] => ID [visible] => 1 [delta] => 2 ) )
.
.
.
//(and so on)
I'd like to write a function that will return "REF100019" by supplying the value of the field_id => 37325091.
Some things I have tried that I couldn't get to work:
foreach
and new RecursiveIterator although the tutorials I read weren't useful for my case here.
Even though the array looks complicated, I think it will be easy since I already have the field id of the parent array.
Thank you in advance for any guidance or sample codes that will work!
Background: This is a part of the response I get from Podio after submitting a request to their API. I just don't know how to take that response and get the piece I need (the ID) so that I can echo it for users).
EDIT: Thank you Orangepill and Barmar for the support. I tried your code. But was getting an error, which made me realize I hadn't given you the full array. I figured out how to get the Podio response to display in a more readable format (I was reading the full JSON response before from the Podio debug file which was super confusing), and figured out the full array is actually structured as I have shown below.
I then took your code and was able to figure out how to make it work for my scenario (see below). Very proud of myself considering I have never written any code before, but I couldn't have done it without your help! Thanks again!
$Arraytosearch = Array(
[items] => Array(
[0] => PodioItem Object(
[_attributes] => Array(
[fields] => Array (
[x] => PodioTextItemField Object (
[__attributes] => Array(
[field_id] => 37325091
[values] => Array(
[0] => Array(
[value] => REF100019 ) )
Note: For anyone who is new to programming like myself and wants the Podio response (or any JSON string) to display in a "pretty" readable format like above, use the code (from Display an array in a readable/hierarchical format thanks to Phenex):
print "<pre>";
print_r($Arraytoformat);
print "</pre>";
And finally, the full code I used (using Orangepill's answer below) which searches the objects and arrays and gives me what I have been searching for for days now is as follows:
$Arraytosearch = PodioItem::filter(APP_ID, $filterParams);
$fieldID = 37325091;
function getFirstValueByFieldId($fieldId, $Arraytosearch){
foreach($Arraytosearch["items"][0]->__attributes["fields"] as $textitem){
if ($textitem->__attributes["field_id"] == $fieldId){
return $textitem->__attributes["values"][0]["value"];
}}}
$refID = getFirstValueByFieldId($fieldID, $Arraytosearch);
The podio-php library has built-in methods that handle all this for you. There's no need to mess with the __attributes property yourself.
You can see a bunch of examples at https://github.com/podio/podio-php/blob/master/examples/items.php
In your case:
// Get item collection
$itemCollection = PodioItem::filter(APP_ID, $filterParams);
$fieldID = 37325091;
foreach ($itemCollection['items'] as $item) {
// Get the field from the item
$field = $item->field($fieldID);
// Now you can print the value of that field
print $field->humanized_value;
// Or if you don't want to have the content sanitized:
print $field->values[0]['value'];
}
There is a lot of ways to skin this cat... this is probably the most straight forward
function getFirstValueByFieldId($fieldId, $Arraytosearch){
foreach($Arraytosearch["fields"] as $textitem){
if ($textitem->__attributes["field_id"] == $fieldId){
return $textitems->__attributes["values"][0]["value"];
}
}
}
to Use in your case would be
echo getFirstValueByFieldId("37325091", $Arraytosearch);
Basically it walks the elements in the fields array and returns the value in the first associated value in the values array where field_id is equal to the parameter of the function.

Categories