Exclude the first result from an Array - php

I am currently messing around with iTunes Api and have ran into a problem with the returning process of albums track list returning the first result as the actual album data instead of the tracklist.
$loop['artist_name'] = $counted[$x]->artistName;
$loop['album_id'] = $counted[$x]->collectionId;
$loop['album_name'] = $counted[$x]->collectionName;
$loop['track_number'] = $counted[$x]->trackCount;
$loop['artwork_url'] = $counted[$x]->artworkUrl100;
$loop['copyright'] = $counted[$x]->copyright;
$loop['genre'] = $counted[$x]->primaryGenreName;
$loop['release_date'] = $counted[$x]->releaseDate;
$data_b = file_get_contents('https://itunes.apple.com/lookup?id='.$loop['album_id'].'&entity=song');
$response_ab = json_decode($data_b);
print '<pre>';
print_r($response_ab);
print '</pre>';
The above portion for print_r returns the following data.
[results] => Array
(
[0] => stdClass Object
(
[wrapperType] => collection
)
[1] => stdClass Object
(
[wrapperType] => track
)
Then continues onward down the track list, how can I remove the first [0] option from my loop? It appears this only returns the album name anyway when I am trying to get the tracklist.

I didn't test the below code however it should work.
$data_b = file_get_contents('https://itunes.apple.com/lookup?id='.$loop['album_id'].'&entity=song');
$response_ab = json_decode($data_b);
$count = $response_ab->results;
$arr = count($count);
for($a = 1; $a < $arr; $a++) {
// do some cool stuff here
}

Related

Appending new data to object

I'm stuck trying to append new data to an stdClass object that I'm creating for an AMchart
I'm returning all the rows I want from the DB, then creating a new object and looping through the returned array, but rather than appending what I want to the end of the existing object, it just gets overwritten. PHP objects dont have an append or push method, so how do you accomplish this?
Here's what my code looks like. Am I missing something simple?
$sql = 'SELECT
count(*) as clients,
STR_TO_DATE(Appt_date, \'%m/%d/%Y\') AS date,
SUM(wait_time) as total_wait_time
FROM tb_by_client
WHERE status = #qualifier
GROUP BY Appt_date';
$rows = $db->fetchAll($sql);
$chartObject = new stdClass();
foreach($rows as $row){
$row->average = round($row->total_wait_time / $row->clients);
$chartObject->date = $row->date;
$chartObject->average = $row->average;
}
$chartArray[] = $chartObject;
return json_encode($chartArray);
So instead of getting something that looks like this
[{"date":"2018-10-01","average":12},{"date":"2018-10-02","average":-33},{"date":"2018-10-04","average":23},{"date":"2018-10-05","average":6}]
I get back just a single
[{"date":"2018-10-01","average":12}]
Because each loop overwrites the last key and value
How do you append instead?
Your problem is you overwrite the data without saving it
$chartObject = new stdClass();
foreach($rows as $row){
$row->average = round($row->total_wait_time / $row->clients);
$chartObject->date = $row->date;
$chartObject->average = $row->average;
}
$chartArray[] = $chartObject;
See on each iteration of foreach($rows as $row){ you change the data in $chartObject, but you never save in your $chartArray.
Do this instead
foreach($rows as $row){
$chartObject = new stdClass(); //new instance of stdClass, obj pass by refrence
$row->average = round($row->total_wait_time / $row->clients);
$chartObject->date = $row->date;
$chartObject->average = $row->average;
$chartArray[] = $chartObject;
}
Personally I wouldn't even bother with using an object:
foreach($rows as $row){
$average = round($row->total_wait_time / $row->clients);
$chartArray[] = ['date'=>$row->date,'average'=>$average];
}
When you JSON Encode an array with string keys, it will make it the correct Javascript Object structure. So there really is no need to keep all those objects in memory and the code is much smaller, cleaner, and easier to read.
One last thing I hinted at in the code, is that objects are pass by reference in PHP (now), and if you don't create a new instance of the object for each iteration, you will actually update all references to the object. This can be illustrated like this:
$obj = new stdClass;
$objects = [];
for($i=0;$i<3;++$i){
$obj->foo = $i;
$objects[] = $obj;
print_r($objects);
}
Output:
Array
(
[0] => stdClass Object
(
[foo] => 0
)
)
Array
(
[0] => stdClass Object
(
[foo] => 1
)
[1] => stdClass Object
(
[foo] => 1
)
)
Array
(
[0] => stdClass Object
(
[foo] => 2
)
[1] => stdClass Object
(
[foo] => 2
)
[2] => stdClass Object
(
[foo] => 2
)
)
Sanbox
Each array is a single iteration of the for loop, this is the same array with another row added after each iteration.
As you can see each copy (its not really a copy) is updated by reference in the array. Basically we have stored the same object (instance ,will call him Bob) 3 times, instead of 3 separate objects (Bob, Alice, John).
If the data you stored was the color of a persons shirt, when Bob puts on a red shirt, he has a red shirt on, but Alice and John don't.
Because of this you need to create a new instance of the object for each iteration and store that.
Hope that helps!
You can do the maths in the SQL and it cuts out the loop altogether...
$sql = 'SELECT STR_TO_DATE(Appt_date, \'%m/%d/%Y\') AS date,
round(SUM(wait_time)/count(*)) as average
FROM tb_by_client
WHERE status = #qualifier
GROUP BY Appt_date';
return json_encode($db->fetchAll($sql));
You're misunderstanding what should be in the loop and what shouldn't.
This should be fine:
$sql = 'SELECT
count(*) as clients,
STR_TO_DATE(Appt_date, \'%m/%d/%Y\') AS date,
SUM(wait_time) as total_wait_time
FROM tb_by_client
WHERE status = #qualifier
GROUP BY Appt_date';
$rows = $db->fetchAll($sql);
$chartArray = [];
foreach($rows as $row){
$row->average = round($row->total_wait_time / $row->clients);
$chartObject = new stdClass();
$chartObject->date = $row->date;
$chartObject->average = $row->average;
$chartArray[] = $chartObject;
}
return json_encode($chartArray);

PHP - get value from JSON

Before i decode my JSON i get this result:
{
"1":[{"membership_id":1,"group_id":1,"user_id":1},
"2":[{"membership_id":3,"group_id":1,"user_id":2}
}
How would i specify that i want to select the one who has 'user_id' == 2 and return membership_id value?
My attempt, but i get undefined value 'user_id':
$myjson = json_decode($s_o, true);
foreach ($myjson as $key => $value){
if($value['user_id'] == $cid){
$mid = $value['membership_id'];
}
}
echo $mid;
Basically i guess i would first have to select the right object and go through it with the foreach, but here i got a bit lost in the situation.
Use Array-Functions:
$json = '{
"1":[{"membership_id":1,"group_id":1,"user_id":1}],
"2":[{"membership_id":3,"group_id":1,"user_id":2}]
}';
$array = json_decode($json, true);
$searchUserID = 2;
$filteredArray = array_filter($array, function($elem) use ($searchUserID){
return $searchUserID == $elem[0]['user_id'];
});
$mid = array_column(array_shift($filteredArray), 'membership_id')[0];
echo "Membership-ID: ".$mid;
array_filter uses a callback function that iterates over every element of the array. If the callback function returns true, that element is assigned to $filteredArray. No need for a foreach loop that way.
But the return value is the whole array element:
Array
(
[2] => Array
(
[0] => Array
(
[membership_id] => 3
[group_id] => 1
[user_id] => 2
)
)
)
So you have to extract your membership_id.
Read the following line from inside out.
First, we fetch the first entry of the array with array_shift (since we have only one entry, this will be our desired entry).
Array
(
[0] => Array
(
[membership_id] => 3
[group_id] => 1
[user_id] => 2
)
)
We pass this array on to array_column to find the entry in the encapsulated array with the column name membership_id. Since array_column again returns an array,
Array
(
[0] => 3
)
we get the (one and only) entry by adding [0] to the end of this command.
Since the last part is a little complicated, here's a torn apart version of it:
$firstEntryOfFilteredArray = array_shift($filteredArray);
$arrayWithValueOfColumnMembershipID = array_column($firstEntryOfFilteredArray, 'membership_id');
$membership_id = $arryWithValueOfColumnMembershipID[0];
These three lines are concatenated into this:
$mid = array_column(array_shift($filteredArray), 'membership_id')[0];
here's a working example: http://sandbox.onlinephpfunctions.com/code/8fe6ede71ca1e09dc68b2f3bec51743b27bf5303
I'm assuming the JSON actually looks like:
{
"1":[{"membership_id":1,"group_id":1,"user_id":1}],
"2":[{"membership_id":3,"group_id":1,"user_id":2}]
}
Each element of the object is an array for some reason. So you need to index it with $value[0] to access the object contained inside it.
$myjson = json_decode($s_o, true);
foreach ($myjson as $key => $value){
if($value[0]['user_id'] == $cid){
$mid = $value[0]['membership_id'];
break;
}
}
echo $mid;
If the arrays can contain multiple elements, you'll need nested loops.
$myjson = json_decode($s_o, true);
foreach ($myjson as $key => $value){
foreach ($value as $object) {
if($object['user_id'] == $cid){
$mid = $object['membership_id'];
break 2;
}
}
}
echo $mid;
This is a bit speculative, but I think the data is indexed by user ID. If that's the case, it makes the lookup much simpler.
After decoding with $myjson = json_decode($s_o, true);
Just find the record by ID and get the membership_id from the matching row.
$membership_id = reset($myjson['2'])['membership_id'];`
You should probably verify that that ID exists, so maybe something like:
$membership_id = isset($myjson['2']) ? reset($myjson['2'])['membership_id'] : null;
If I'm wrong and the fact that the row numbers match the user_id is just a coincidence, then never mind :)

Selecting a nested stdClass Object

Hi I was wondering if it is possible to grab:
Here is my current code:
<?php
include('php-riot-api.php');
$region = 'euw';
$grab_id = 19631093;
$instance = new riotapi($region);
$grab_dataB = $instance->getStats($grab_id);
$decode_dataB = json_decode($grab_dataB);
$grab_tier = $decode_data->{'aggregatedStats[7].Unranked[wins]'};
print_r($decode_dataB);
?>
This is my result:
http://2v2.lolnode.com/testing.php (http://pastebin.com/DrJDnuaC)
I would like to be able to get the numbered result for Unranked[wins] (which is [aggregatedStats] => stdClass Object ( ) ) [7])
You can get directly:
$grab_tier = $decode_dataB->playerStatSummaries[7]->wins;
But you won't know for sure that the 8'th key is the one you want, or ...
You can loop in your results:
$unranked = '';
foreach($decode_dataB->playerStatSummaries as $summary){
if($summary->playerStatSummaryType == 'Unranked'){
$unranked = $summary;
break;
}
}
print_r($unranked);
and get values, eg $unranked->wins
you can json_decode with 2'nd parameter true (object is transformed into array) and loop like a normal array.
$decode_dataB = json_decode($grab_dataB, true);

How to split an Array into usable data, so it can be counted and manipulated

I have this query:
SELECT carID FROM reservations WHERE startDate < '".$sqlretdate."' AND endDate > '".$sqlcoldate."' OR startDate = '".$sqlcoldate."' OR endDate = '".$sqlretdate."'"
Using a loop:
while($presentid = mysql_fetch_array($checkreservations)) {
This returns an array of data, so for example:
echo "<---space-->";
print_r($presentid['carID']);
Would display:
<---space-->11<---space-->10<---space-->2<---space-->8<---space-->9<---space-->7
This is a list of ids, I need to do something with each of them.
I can explode it:
print_r(explode(" ", $presentid['carID']));
And this would make it print like this:
Array ( [0] => 11 ) Array ( [0] => 10 ) Array ( [0] => 2 ) Array ( [0] => 8 ) Array ( [0] => 9 ) Array ( [0] => 7 )
How do I totally split each id and store it into a variable, so I can use them to do something else?
In this case each ID is unique to a car, and has a model name associated to it, so I want to use the id to find out which model name is related to it, count the number of that model name in the database, and then check to see how many of the returned ids related to that model, and therefore how many there is left. I hope that makes sense.
In your while loop, $presentid represents each row in the result set. $presentid['carID'] is not an array! It's one carID value. You do not need to use explode here at all.
while($presentid = mysql_fetch_array($checkreservations)) {
// This *is* each car ID! Do with it what you want.
$carID = $presentid['carID'];
}
$ids = array();
$count = 0;
while($presentid = mysql_fetch_array($checkreservations)) {
$ids['car_' . $count++] = $presentid['carID'];
}
extract($ids);
This will give you independent variables:
$car_0 = 11;
$car_1 = 12;
$car_2 = 2;
..etc
You can't store it into a basic variable without overwriting it, unless you want to reserve very many variables, It's best to go through the loop, store the values into an array, then you can walk trough the array once the while loop is over, unless you can just do something with them right away.
"How do I totally split each id and store it into a variable"
while($presentid = mysql_fetch_array($checkreservations))
{
$carId = $presentid['carID'];
$array[] = array('id' => $carId );
}
So you can parse through the array once It's over.

Problems accessing and updating data within serialized array

I was hoping someone might be able to help me out or point me in the right direction. I've spent a week trying to figure out how to access and update the weight field in WP ecommerce and Ive had no success at accessing it and updating new values.
The script I'm using access a website to scrape comic book info. It then parses the data from the xml file and assigns variables for the second is for values that are specific to WP Ecommerce.
The whole script works beautifully and creates product pages for each comic book and all data is added into each product. Except for one! and I've been stuck for a week trying to figure out how to access the meta and update it. That's the _wpsc_product_metadata array for weight and weight_unit and other meta values that are stored within.
A comic weighs roughly 3 ounces and I've been trying to assign this value to each card as it's created "3" and "ounce" - I've been unsuccessful.
I've tried probably over so many different ways from digging into the ecommerce code to looking on the net, reading about multidimensional arrays, serialized arrays and it isn't clicking in my noggin'. Keep in mind I've only been programming in PHP for the past month, and prior to a month ago I knew nothing about code other than when I dabbled in C and C++ 15 years ago. Back then, it was mainly copying existing code and changing the outputs in MUDS (multi-user dungeons) - back when online gaming was text-based, lol.
I assumed I could access WP Ecommerce meta by using:
get_post_meta($post_id, '_wpsc_product_metadata', true); That did not work.
Other methods of accomplishing this I tried:
get_post_meta(get_the_id($post_id), '_wpsc_product_metadata', true); // no success
I tried specific product ids using it like so:
get_the_id(300), or just '300', i've used single quotes double quotes no qoutes, "{}", etc etc etc etc
Now when I've used:
get_post_meta($post_id, ''); //while in the loop
The values for SKU and price are outputted but not what's within _wpsc_product_metadata
Then when i use this:
$product_data['meta'] = array();
$product_data['meta'] = maybe_unserialize(get_post_meta('$post_id', '' ));
This is what I get when I print_r
Array ( [_wpsc_price] => Array ( [0] => Array ( [0] => 19.99 ) )
[_wpsc_sku] => Array ( [0] => Array ( [0] => 978-0-7851-5209-5 ) ) )
So I tried one more thing I went into a specific product and i manually set weight to 5 and I changed the code as follows:
$product_data['meta'] = array();
$product_data['meta'] = maybe_unserialize(get_post_meta( '44317', '' ));
This is the output:
Array ( [_wpsc_stock] => Array ( [0] => Array ( [0] => ) )
[_wpsc_product_metadata] => Array ( [0] => Array ( [0] =>
a:19:{s:25:"wpec_taxes_taxable_amount";s:0:"";s:13:"external_link";s:0:
"";s:18:"external_link_text";s:0:"";s:20:"external_link_target";s:0:"";s:6:
"weight";s:3:"0.3";s:11:"weight_unit";s:5:"pound";s:10:"dimensions";a:6:
{s:6:"height";s:1:"0";s:11:"height_unit";s:2:"in";s:5:"width";s:2:"0
";s:10:"width_unit";s:2:"in";s:6:"length";s:1:"0";s:11:"length_unit";
s:2:"in";}s:8:"shipping";a:{s:5:"local";s:1:"0";s:13:"international";s:1:"0";}
s:14:"merchant_notes";s:0:"";s:8:"engraved";s:1:"0";s:23:
"can_have_uploaded_image";s:1:"0";s:15:"enable_comments";s:0:"";
s:24:"unpublish_when_none_left";s:1:"0";s:11:"no_shipping";s:1:"0";s:16:
"quantity_limited";s:1:"0";s:7:"special";s:1:"0";s:17:"display_weight_as";s:5:
"pound";s:16:"table_rate_price";a:2:{s:8:"quantity";a:0:{}s:11:"table_price";a:0:
{}}s:17:"google_prohibited";s:1:"0";} ) ) [_wpsc_special_price] => Array ( [0] =>
Array ( [0] => 0 ) ) [_edit_last] => Array ( [0] => Array ( [0] => 1 ) )
[_edit_lock] => Array ( [0] => Array ( [0] => 1333358836:1 ) ) [_wpsc_sku] =>
Array ( [0] => Array ( [0] => 978-0-7851-6421-0 ) ) [_wpsc_price] => Array
( [0] => Array ( [0] => 24.99 ) ) [_wpsc_is_donation] => Array ( [0] => Array (
[0] => 0 ) ) [_wpsc_currency] => Array ( [0] => Array ( [0] => a:0:{} ) ) )
I was hoping, no I'm begging that someone might be able to enlighten me and show me how to access and update this data that is stored in _wpsc_product_metadata specifically weight and weight_unit and it would be even better if you do know how, you could show me an example of updating a newly created posts weight to a value and changing the default weight_unit from pounds to ounces.
Here is the code for reference:
<?php
function scraping_comic()
{
$html = file_get_html('http://site-to-strip.com/');
$matches = str_replace (' ', ' ', $article);
foreach($html->find('li.browse_result') as $article)
{
// get comic title
$item['title'] = trim($article->find('h4', 0)->find('span',0)->outertext);
// get comic title url
$item['title_url'] = trim($article->find('h4', 0)->find('a.grid-hidden',0)->href);
// get comic image
$item['image_url'] = trim($article->find('img.main_thumb',0)->src);
// get comic excerpt
$item['excerpt'] = trim($article->find('p.browse_result_description_release', 0)->plaintext);
// get comic sales info
$item['on_sale'] = trim($article->find('.browse_comics_release_dates', 0)->plaintext);
// strip numbers and punctuations
$item['title2'] = trim(preg_replace("/[^A-Za-z-\t\n\s]/","",$article->find('h4',0)->find('span',0)->plaintext));
$item['title3'] = trim(preg_replace("/[^A-Za-z]/","",$article->find('h4',0)->find('span',0)->plaintext));
$ret[] = $item;
}
$html->clear();
unset($html);
return $ret;
}
$ret = scraping_comic();
if ( ! empty($ret))
{
foreach($ret as $v)
{
//download the image
$url = $v['image_url'];
$title = $v['title3'];
$now = time();
$num = date("w");
if ($num == 0)
{ $sub = 6; }
else { $sub = ($num-1); }
$WeekMon = mktime(0, 0, 0, date("m", $now) , date("d", $now)-$sub, date("Y", $now));
$todayh = getdate($WeekMon);
$d = $todayh[mday];
$m = $todayh[mon];
$y = $todayh[year];
$date_stamp = $d.$m.$y;
//scrape inside pages
$scrape = 'http://domain.com';
$comic_details = $v['title_url'];
$comic_details_url = $scrape.$comic_details;
$url2 = file_get_html($comic_details_url);
foreach($url2->find('.comics_detail_lead_left_panel_content') as $the_details);
$matches = str_replace (' ', ' ', $the_details);
{
$item2['image2_url'] = trim($the_details->find('img.frame-img',0)->src);
$item2['full_desc'] = trim($the_details->find('p',0)->plaintext);
$item2['data'] = trim($the_details->find('dl',0)->plaintext);
}
$url2->clear();
unset($url2);
//download medium-sized image
$root2 = ('/home/****/public_html/wp-content/blogs.dir/14/files/comics/' .$title.$date_stamp. '-medium.jpg');
$image2 = $item2['image2_url'];
copy($image2, $root2);
unset($root2);
unset($image2);
//match specific data and assign variables
$string = $item2['data'];
$number = preg_match("/(Comic|Hardcover|Paperback)[^A-Za-z]+/", $string, $fields);
switch ($fields[1])
{
case ('Comic'):
$cat = array(51, 52);
break;
case ('Hardcover'):
$cat = array(85, 52);
break;
case ('Paperback'):
$cat = array(95, 52);
break;
default: "";
}
$number = preg_match("/((January)|(February)|(March)|(April)|(May)|(June)|(July)|(August)|(September)|(October)|(November)|(December))[^A-Za-z0-9,]+[A-Za-z0-9,\s]+/", $string, $fields);
$date = $fields[0];
$number = preg_match("/((UPC)|(ISBN))[^0-9-]+([0-9-]+)/", $string, $fields);
$upc = $fields[4];
$number = preg_match("/((Price))[^0-9.]+([0-9.\s]+)/", $string, $fields);
$price = $fields[3];
$full_desc = $item2['full_desc'];
$maintitle = $v['title'];
$excerpt = $v['excerpt'];
$comic_post = array();
$comic_post['post_title'] = wp_strip_all_tags($maintitle);
$comic_post['post_content'] = wp_strip_all_tags($full_desc);
$comic_post['post_status'] = 'publish';
$comic_post['post_author'] = 1;
$comic_post['post_type'] = 'wpsc-product';
$comic_post['post_category'] = $cat;
$comic_post['comment_status'] = 'closed';
$comic_post['ping_status'] = 'closed';
$comic_post['post_excerpt'] = wp_strip_all_tags($excerpt);
// create comic book
$post_id = wp_insert_post( $comic_post );
// category insertion does not work fixed this by calling wp_set_post_terms
wp_set_post_terms($post_id, $cat, 'wpsc_product_category' );
$wpsc_custom = update_post_meta;
$wpsc_custom($post_id, '_wpsc_price', $price);
$wpsc_custom($post_id, '_wpsc_sku', $upc);
//Gain access to WP Ecommerce meta data and assign new values to weight ***IN PROGRESS***
$product_data['meta'] = array();
$product_data['meta'] = maybe_unserialize(get_post_meta( $post_id, '' ));
//***TESTING***//
echo '<br /> the data <br />';
print_r($product_data['meta']);
//Set featured image for product
$filename = ('comics/' .$title .$date_stamp. '-medium.jpg');
update_post_meta( $post_ID, 'image_thumbnail', $imgloc );
set_featured_image($post_id, $filename);
}
}
else { echo 'Could not scrape site!'; }
?>
With help from a WP E-commerce contributor here's the missing puzzle piece to update weight.
if(!isset($product_data['meta']) || !is_array($product_data['meta'])) {
$product_data['meta'] = array();
}
if(!isset($product_data['meta']['_wpsc_product_metadata'])) {
$product_data['meta']['_wpsc_product_metadata'] =
maybe_unserialize(get_post_meta($post_id, '_wpsc_product_metadata', true));
}
if(!is_array($product_data['meta']['_wpsc_product_metadata'])) {
$product_data['meta']['_wpsc_product_metadata'] = array();
}
$product_data['meta']['_wpsc_product_metadata']['weight_unit'] = 'ounce';
$product_data['meta']['_wpsc_product_metadata']['weight'] = 0.19;
update_post_meta($post_id, '_wpsc_product_metadata', $product_data['meta']['_wpsc_product_metadata']);
for someone that has not programmed for so long and has only recently looked into PHP you do seem to be doing quite well.
Regarding the array. _wpsc_product_metadata appears to be JSON. You should look towards the PHP manual particularly the section related to JSON as linked below.
http://php.net/manual/en/book.json.php
If you use json_decode you will be able to retrieve an object that has the attributes that you require as properties for the object.

Categories