Get array object data from exploded array fields in foreach loop - arrays

I'm trying to extract data from our JSON data based on given output fields, but I'm not getting a good result.
e.g.
Given fields that I want:
Array
(
[0] => id
[1] => name
[2] => email
[3] => optin_email
)
Those fields exist in my datastring, I want to export those to a CSV.
I can do this, hardcoded
foreach ($jsonString as $value) {
$row = [
$value->id,
$value->name,
$value->email,
$value->phone
];
print_r($row);
}
The above will give me the list/file I need. BUT, I want to make that dynamic based on the data in the array, so, fo rexample, when this is the Array:
Array
(
[0] => id
[1] => name
)
This should be my output:
foreach ($jsonString as $value) {
$row = [
$value->id,
$value->name
];
print_r($row);
}
So I need to dynamicly create the
$value->{var}
I have been trying forever, but I am not seeing it straight anymore.
Tried this:
$rowFields = '';
foreach ($export_datafields AS $v) {
$rowFields .= '$value->' . $v . ',';
}
$trimmed_row_fields = rtrim($rowFields, ',');
foreach ($jsonString as $value) {
$row = $trimmed_row_fields;
print_r($row);
}
And several variations of that:
foreach ($jsonString as $value) {
$row = [$trimmed_row_fields];
print_r($row);
}
Question is: how can I get
$value->VAR
as a valid array key when I only know the VAR name and need the prefixed $value-> object.

I ended up using the following code which works for me. If anybody still has the answer to my original question, please shoot. Always good to know it all.
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=$csvFileName");
header("Pragma: no-cache");
header("Expires: 0");
$new_row = implode(",", $export_datafields) . "\n";
foreach ($jsonString as $value) {
foreach ($export_datafields AS $v) {
$new_row .= $value->$v . ',';
}
$new_row = substr($new_row, 0, -1);
$new_row .= "\n";
}
echo $new_row;

Related

Undefined array key 1 in foreach loop

i have this piece of code. On the top i download text data from URL and i get string. This string has some uninportant text so this text is in $info and important number are in $array than i did some reIndex array because for some reason i had $array[0] empty.
I have 2 array: $array and $array_try both arrays shoud have similar structure as u can see here:
For some reason im getting Undefined array key 1 in this line $array_value[] = $parts[1];
When i change in foreach loop $array for $array_try it works well.
Best
$data = file_get_contents("$url");
$data = explode('Kurz', $data);
$kurz = '|Kurz';
$info= substr_replace($data[0], $kurz, -1, );
echo "<br>";
$array = explode ("\n", $data[1]);
//foreach ($array as $value){
// echo $value . "<br>";
//}
unset($array[0]);
$array = array_values($array);
$array_try = [
"04.01.2021|26,140",
"05.01.2021|26,225",
"06.01.2021|26,145"
];
$array_date = [];
$array_value = [];
foreach($array as $value) {
$parts = explode('|', $value);
$array_date[] = $parts[0];
$array_value[] = $parts[1];
}
var_dump($array_try);
echo "<br>";
echo "<br>";
var_dump($array);

How to extract all URL's from webpage in an array an see if certain value is there

I am trying to extract all the links from a webpage and put them into an array that I can then compare values with to see if there is a match. The problem that I'm having is I cannot seem to get the values into an array. I am able to see all the links and I see that there is a match with the one I'm trying to compare with but it's not recognizing that it's there. My code is as follows. Any help would be greatly appreciated.
$content = file_get_contents("sample_url");
$content = strip_tags($content, "<a>");
$subString = preg_split("/<\/a>/", $content);
$items = array();
foreach ( $subString as $val ){
if( strpos($val, "<a href=") !== FALSE ) {
$val = preg_replace("/.*<a\s+href=\"/sm", "", $val);
$val = preg_replace("/\".*/", "", $val);
$items[] = $val;
var_dump($val . "<br />");
}
}
if (in_array($testing_link, $items, true)) {
echo 'It is here!';
}
else {
echo 'it is NOT here :( ';
}
Better to use the DOMDocument to get the links into an array. Like this:
$doc = new DOMDocument();
// the string containing all the URLs and stuff
$doc->loadHTML($content);
//Extract the links from the HTML. From https://thisinterestsme.com/php-find-links-in-html/
$links = $doc->getElementsByTagName('a');
//Array that will contain our extracted links.
$extracted_links = array();
//Loop through the DOMNodeList.
//We can do this because the DOMNodeList object is traversable.
foreach ($links as $link) {
//Get the link text.
//$linkText = $link->nodeValue;
//Get the link in the href attribute.
$linkHref = $link->getAttribute('href');
}
Now all the HREFS are in the $linkHref array.
Better to use DOMDocument rather than RegEx. Much easier, and more accurate and consistent in results.

Merging and adding values of 2 JSON feeds in PHP

I'm trying to write a shopping list app for a website which already has ingredients listed in JSON.
The full code is at the bottom, but just to explain; What I'm aiming to do is to be able to merge the 2 arrays, adding the values from the 'quantity' when the 'name' (and preferably also the 'measure') matches.
e.g. 'Sunflower oil' is listed in both JSON feeds.
I want it to output as:
{"name":"Sunflower oil","quantity":110,"measure":"ml"}
but it currently overwrites the JSON and the output is:
{"name":"Sunflower oil","quantity":10,"measure":"ml"},
Any assistance in what I'm doing wrong would be greatly appreciated as JSON and objects/arrays aren't my strong point!
Thanks in advance - here's my code:
<?php
$a = '{"ingredients":[{"name": "Sunflower oil","quantity": 100,"measure": "ml"}]}';
$b = '{"ingredients":[{"name": "Sunflower oil","quantity": 10,"measure": "ml"},{"name": "Fennel seeds","quantity": 1,"measure": "teaspoon"},{"name": "Garlic","quantity": 1,"measure": "clove"}]}';
print_r( json_encode(array_merge(json_decode($a, true),json_decode($b, true))) );
?>
You can use the following code to get the expected result:
<?php
$a = '{"ingredients":[{"name": "Sunflower oil","quantity": 100,"measure": "ml"},{"name": "Olive oil","quantity": 50,"measure": "ml"}]}';
$b = '{"ingredients":[{"name": "Sunflower oil","quantity": 10,"measure": "ml"},{"name": "Fennel seeds","quantity": 1,"measure": "teaspoon"},{"name": "Garlic","quantity": 1,"measure": "clove"}]}';
$aArr = json_decode($a, true);
$bArr = json_decode($b, true);
$sumArr = array("ingredients" => array());
foreach ($aArr['ingredients'] as $valA) {
foreach ($bArr['ingredients'] as $keyB => $valB) {
if ($valA['name'] == $valB['name'] &&
$valA['measure'] == $valB['measure']) {
$valA['quantity'] += $valB['quantity'];
$sumArr['ingredients'][] = $valA;
unset($bArr['ingredients'][$keyB]);
continue 2;
}
}
$sumArr['ingredients'][] = $valA;
}
$sumArr['ingredients'] = array_merge($sumArr['ingredients'], $bArr['ingredients']);
print_r( json_encode( $sumArr ));
?>

Wordpress use array key and value to set data attribute

I have setup an array of product values. I need to set each array key to the data-attribute and the value to the data-attribute value
<li data-name="product1" data-price="49.99" data-rating="4.5"></li>
So in Wordpress I have this filter hook
function product_data_sorting( $product_attrs, $product, $terms) {
global $post;
// Product Attributes
$product_attrs['name'] = $post->post_name;
$product_attrs['price'] = $product->price;
$product_attrs['rating'] = $product->get_average_rating();
$product_attrs['newness'] = $post->post_modified;
// Product Categories
foreach ($terms as $term) {
$categories[] = $term->slug;
}
$product_attrs['categories'] = $categories;
foreach ($product_attrs as $attribute) {
if ( is_array($attribute) ) {
//This is a category
}
else {
$results[] = 'data-' . $key . '="' . '$attribute' . '"';
}
}
return $results
}
add_filter( 'add_sorting', 'product_data_sorting', 10, 3 );
I am getting all the correct data pushed in to the $product_attrs array that I need, but not sure how to work with the array key and values so that in the $results array it would be formatted like this:
$results = (data-name="product1", data-price="49.99", data-rating="4.5");
Hope that makes some sense
thanks
You would need key=>value pair within foreach.
$ignored = array ('newness'); // array to maintain what attributes you want to ignore
foreach ($product_attrs as $key => $attribute) {
if ( is_array($attribute) ) {
//This is a category
}
else {
if(!inarray($key, $ignored)
$results[] = 'data-' . $key . '="' . $attribute . '"';
}
}
Also note that $attribute isn't enlcosed in single quotes as you have in the question. Variables inside single quote can not be parsed

Warning message in older perl version

I have the following code in my script:
while (my ($key, $value) = each #values) {
if ( $key < $arraySize-1) {
if ( $values[$key+1] eq "user") {
$endcon=1;
}
}
if ( ( $startcon == 1 ) && ( $endcon != 1 ) ) {
$UptimeString .= $value;
}
if ( $value eq "up") {
$startcon=1;
}
if ( $value eq "average:") {
$LoadMinOne=$values[$key+1];
}
}
While compiling it, in perl 5.14, I have no warnings, but in perl 5.10.1, I have this warning: Type of arg 1 to each must be hash (not private array) at ./uptimep.pl line 21, near "#values) "
Line 21 is while (my ($key, $value) = each #values) {
What does this mean?
As said in error message, each must have a hash for parameter, but you give it an array.
You could replace this line:
while (my ($key, $value) = each #values) {
by:
for my $key(0 .. $#values) {
my $value = $values[$key];
According to the doc each accepts array as parameter from perl 5.12.0
as it says, each expects a hash as an argument, not an array.
you can populate a hash first ( my %hash = #values; ) and use it as an argument ( while (my ($key, $value) = each %hash) ).

Resources