Change PHP array - php

Hi I have built an array and in the final process of finishing the script.
I have been building a web crawler which scans specific links on sites specified. The crawler stores all the links in one page and then inserts them into another array (news_stories) with the links specified in them.
Now the way the new array is structured is like this.
Array
(
[0] => Array
(
[title] => The Qlick
[description] => Qlick
[keywords] => Search Engine, Web, Sexy, Noah Smith
[link] => http://www.theqlick.com/qlickdates.php
)
)
And that is difficult for me to implode and insert into a mysql table. Now my code below uses functions to grab titles, descriptions etc for each link it finds and then inserts them into the new array if they match.
Is there anyway to get this to delete the Array() at the top of the array and just have the array which specifies the title, description etc.
I want the output to look like:
[0] => Array
(
[title] => The Qlick
[description] => Qlick
[keywords] => Search Engine, Web, Sexy, Noah Smith
[link] => http://www.theqlick.com/qlickdates.php
)
Any ideas?
$bbc_values = array('http://www.theqlick.com/festivalfreaks.php', 'http://www.theqlick.com/qlickdates.php');
$news_stories = array();
foreach ($links as $link) {
$item = array(
"title" => Titles($link),
"description" => getMetas($link),
"keywords" => getKeywords($link),
"link" => $link
);
if (empty($item["description"])) {
$item["description"] = getWord($link);
}
foreach($bbc_values as $bbc_value) {
// note the '===' . this is important
if(strpos($item['link'], $bbc_value) === 0) {
$news_stories[] = $item;
}
}
}
$data = '"' . implode('" , "', $news_stories) . '"';
$query =
//CNN algorithm
print_r($news_stories);

PHP foreach() is an iterator, intended to let your programming perform the same action on a collection of data. In the existing design, the *$news_stories* array can contain multiple individual "sub-arrays", with each such "sub-array" being the unit of data you want to insert into your data base.
When you get down to the part about creating queries, you can use something like this:
foreach ($news_stories as $story)
{
/* CREATE AND RUN QUERY USING DATA IN $story */
}
You can use *var_dump()* to look at the contents of a $story array. When you do that, it will probably make sense instantly. PHP foreach() does not care if you have one element or a hundred elements. If you have zero elements, it will not run the code inside the control structure.

Related

Dynamically finding a particular array index

I have a large multi-dimensional array with multiple occurrences of #options indexes. The following is a single array example:
FORM => Array
(
[#attached] => Array
(
[library] => quiz/quiz-form-styling
)
[text_0] => Array
(
[#type] => markup
[#markup] =>
Wherelese did Walter White work besides being a teacher?
)
[radio_1] => Array
(
[#type] => radios
[#options] => Array
(
[0] => An elder Care home
[1] => [A car wash]
[2] => A beauty saloon
[3] => For Skylers old boss
)
[#correct] => testing_correct_for radio
)
[text_2] => Array
(
[#type] => markup
[#markup] =>
)
)
In the example above, the parent array of #options is radio_1. But that is not always the case as the arrays are dynamically generated. There is no way to know in advance what the parent index would be but there is always an #options index.
What I'm trying to figure out is how to find and retrieve the data in all occurrences of #options. How can I do that?
I'd suggest iterating the set of form elements and checking if an inner #options key exists. If so, you can add the options to your array of all options.
$all_options = [];
foreach ($form_elements as $name => $settings) {
if (isset($settings['#options'])) {
$all_options[$name] = $settings['#options'];
}
}
I used the element name as key in the example code, because I thought it seemed like it would be convenient to know where the options came from, but you wouldn't have to do it that way. If you just wanted them all in one big list, you could merge them onto $all_options instead of appending them.
$all_options = array_merge($all_options, $settings['#options']);
This is assuming each of the values under FORM is an array representing one form element. If there is any nesting such that #options could appear at a deeper level, a recursive search could handle that, but if not, I think it's best to keep it simple.
You can try something like recursive function
Here is simple example for above case.
$alloptions = array();
function seach($searcharray){
foreach($searcharray as $key=>$value){
if($key == '#options'){
$alloptions[] = $searcharray[$key];
}else if(is_array($value)){
seach($value);
}
}
}

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'];
}
}

PHP str_replace is not replacing value

I've been bashing my head against the wall for a couple of days on this, because all indications are that this SHOULD work, so I'm obviously missing something simple.
First I am using a function to grab an array of user submitted comments
function get_id_comment_info($id) {
global $connection;
$pdo = new PDO('mysql:host='.DB_SERVER.'; dbname='.DB_NAME, DB_USER, DB_PASS);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('SET NAMES "utf8"');
$sql = "SELECT parks.parkid, parks.state, pcomment.parkid, pcomment.comment, pcomment.logname
FROM parks
LEFT JOIN pcomment
ON parks.parkid=pcomment.parkid
WHERE parks.id = '$id'";
$result = $pdo->query($sql);
$cominfo = $result->fetchAll();
return $cominfo;
}
Then, inside of a foreach loop which processes each park by id, I am working with the data:
foreach ($display_result as $parkrow) {
$id = $parkrow['parkid'];
$comments = get_id_comment_info($id);
$cleancom = str_replace("'", '', $comments);
print_r($cleancom);
.
.
.
}
The output for $cleancom is:
Array ( [0] => Array ( [parkid] => 462 [0] => 462 [state] => KS [1] =>
KS [2] => 462 [comment] => I have noticed some others here say don't
waste your time, but I think it's ok. Yes, it's smaller than most, but
there is fun to be had if you are an avid rider. [3] => I have noticed
some others here say don't waste your time, but I think it's ok. Yes,
it's smaller than most, but there is fun to be had if you are an avid
rider. [logname] => John32070 [4] => John32070 ) )
It does not remove the '. If I use preg_replace then the output is simply blank. I am missing something simple, but I just can't see it!
I have tested the str_replace() function and got the following results:
$myArray = array("h'i", array("hi'hi", "yo"));
print_r($myArray);
//RESULT: Array ( [0] => h'i [1] => Array ( [0] => hi'hi [1] => yo ) )
After applying the filter:
$filtered = str_replace( "'", "", $myArray);
print_r($filtered );
//RESULT: Array ( [0] => hi [1] => Array ( [0] => hi'hi [1] => yo ) )
What the previous results show is that any string values inside the top array are indeed being converted (h'i converted to hi) while any values that form part of the multidimensional array (any arrays within arrays) are not hi'hi remained the same. This seems to be how the function was created to work.
One solution is:
$cleancom = [];
foreach ($comments as $key => $value)
{
$cleancom[$key] = str_replace( "'", "", $value );
}
The reason the previous code works is because str_replace() is never being applied to a multidimensional array, while in your previous code it was. The previous code will not work however if you have something like an array within an array within another array, so if that ends up being the case in the future, I suggest you try finding a solution with callback functions.
Let me know if this worked for you.
Want to say something else, you should put the ids in an array, then use MySQL in() function, it only need to execute once, while your method will execute many times.

Get json object from it's position in the list

Let's say this is my json(I wont be able to change this json file):
{"success":true,
"users":{
"1036344647":{"name":"joel", "age":18},
"1036344365":{"name":"klant", "age":24},
"1036344352":{"name":"grabben", "age":23}
}
}
I also have a php code that collect this json data and decodes it.
$data = json_decode(file_get_contents("http://example.com/users/json"));
As you can see in my json each user has a random generated id that will change everytime i collect the data from my json file. Basicly i don't know any of the user ids.
But i still want to be able to print out a users name depending on it's position in the list.
For example: echo $data->users->[THE SECOND ID(the id with a user named "klant")]->name;
So i know this could be done easy if the json file was written as a array, but it is not.
Is there any way i can print out a object in the json depending on it's position in the list?
Try this:
function findUser($id)
{
$data = json_decode(file_get_contents("http://example.com/users/json"));
return isset($data[0]->users->$id) ? $data[0]->users->$id : null;
}
$user = findUser(1036344365);
var_dump($user);
It will output
object(stdClass)#4 (2) { ["name"]=> string(5) "klant" ["age"]=> int(24) }
You can build a 2nd array by "throwing away" those unique IDs with array_values() like so:
$array = json_decode($yourJSON, true);
$justValues = array_values( $array["users"] );
print_r( $justValues );
Output:
Array
(
[0] => Array
(
[name] => joel
[age] => 18
)
[1] => Array
(
[name] => klant
[age] => 24
)
[2] => Array
(
[name] => grabben
[age] => 23
)
)
You can then access each person's data like so:
echo $justValues[1]["name"]; // klant
No, it's not possible. JavaScript objects by design are unaware of "position" of their key-value pairs. Behind the scenes, that's what makes them powerful.
The first step is to rethink why you need to work with the JSON according to position.

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