Store array keys in variable with foreach loop PHP - php

When saving in an array the prices and ids of a product, with this code...
foreach($resource->group->tabs as $tab) {
foreach($tab->articles as $article)
{
$prices_and_ids[] = array(
$article->article_erp_id => array(
'price_pvp' => $article->price_pvp,
'price_promotion' => $article->price_promotion,
)
);
}
}
The result of $prices_and_ids with this code is an object with the keys numbered:
array:10 [▼
0 => array:1 [▼
3140 => array:2 [▼
"price_pvp" => 6.5
"price_promotion" => 5.53
]
]
1 => array:1 [▼
3141 => array:2 [▼
"price_pvp" => 7.5
"price_promotion" => 6.37
]
]
2 ... ... ...
The result I want is that the article ids are the keys of the array.
I want this:
array:10 [▼
3140 => array:1 [▼
"price_pvp" => 6.5
"price_promotion" => 5.53
]
3141 => array:1 [▼
"price_pvp" => 7.5
"price_promotion" => 6.37
] ... ... ...

the problem with your code is your adding it in another array do this
$prices_and_ids[$article->article_erp_id]
instead of
$prices_and_ids[]
foreach($resource->group->tabs as $tab) {
foreach($tab->articles as $article)
{
$prices_and_ids[$article->article_erp_id] = array(
$article->article_erp_id => array(
'price_pvp' => $article->price_pvp,
'price_promotion' => $article->price_promotion,
)
);
}
}

Instead of $prices_and_ids[] you should use $prices_and_ids[$article->article_erp_id]
foreach($resource->group->tabs as $tab) {
foreach($tab->articles as $article)
{
$prices_and_ids[$article->article_erp_id] array(
'price_pvp' => $article->price_pvp,
'price_promotion' => $article->price_promotion,
);
}
}

Change your foreach body as following code
$prices_and_ids[$article->article_erp_id] = array(
'price_pvp' => $article->price_pvp,
'price_promotion' => $article->price_promotion,
);

Related

Filter Array based on if contains php

My aim here is to remove the whole object from the array if "record_type" is null. I should then only be left with data that has a record_type set in the array.
I've looked into the array filter not sure how I target the data within the array "record_type". My only other thought is to import to a database and then SQL query what I want then delete data I've had which is much more overkill.
<pre>
array:36 [▼
0 => array:3 [▼
"type" => "comment"
"line_index" => 0
"text_b64" => "OyBjUGFuZWwgZmlyc3Q6ODguMC4xMiAodXBkYXRlX3RpbWUpOjE2MTg1NDYxNDIgQ3BhbmVsOjpab25lRmlsZTo6VkVSU0lPTjoxLjMgaG9zdG5hbWU6cjExOC5sb24yLm15c2VjdXJlY2xvdWRob3N0LmNvbSBs ▶"
]
1 => array:3 [▼
"line_index" => 1
"text_b64" => "OyBab25lIGZpbGUgZm9yIG9ha3RyZWVkZW50YWxtb3J0aW1lci5jby51aw=="
"type" => "comment"
]
2 => array:3 [▼
"text_b64" => "JFRUTCAxNDQwMA=="
"line_index" => 2
"type" => "control"
]
3 => array:6 [▼
"line_index" => 3
"dname_b64" => "b2FrdHJlZWRlbnRhbG1vcnRpbWVyLmNvLnVrLg=="
"record_type" => "SOA"
"ttl" => 30
"type" => "record"
"data_b64" => array:7 [▶]
]
4 => array:6 [▼
"dname_b64" => "b2FrdHJlZWRlbnRhbG1vcnRpbWVyLmNvLnVrLg=="
"line_index" => 10
"record_type" => "NS"
"ttl" => 30
"type" => "record"
"data_b64" => array:1 [▶]
]
5 => array:6 [▼
"ttl" => 30
"dname_b64" => "b2FrdHJlZWRlbnRhbG1vcnRpbWVyLmNvLnVrLg=="
"line_index" => 11
"record_type" => "NS"
"data_b64" => array:1 [▶]
"type" => "record"
]
</pre>
Goal: only be left with data that has a 'record_type' set (not null) in the array
Solution: use array_filter() on your source array ($arr) and filter for records with 'record_type' != "NS" (assuming "NS" is what you refer to as null, or not set).
<?php
$result = array_filter(
$arr,
function (array $record) {
if (isset($record['record_type'])) {
return $record['record_type'] != "NS";
} return null;
}
);
working demo
EDIT
If you want to filter for only those records that are of a certain type, e.g. type 'record', following should help:
<?php
$result = array_filter(
$arr,
function (array $record) {
if ($record['type'] == 'record') {
return true;
} return false;
}
);
working demo
If your Goal is to filter array to remove any inner-array that hasn't a record_type, So use array_filter with a callback function fn to check that record_type exist with isset function.
array_filter($arr, fn($el)=>isset($el["record_type"]));

Itterate to a multidimensional array

I am trying to iterate over this array in order to take all league values (league_id,name,type etc)
array:1 [▼
"api" => array:2 [▼
"results" => 970
"leagues" => array:970 [▼
0 => array:13 [▼
"league_id" => 1
"name" => "World Cup"
"type" => "Cup"
"country" => "World"
"country_code" => null
"season" => 2018
"season_start" => "2018-06-14"
"season_end" => "2018-07-15"
"logo" => "https://media.api-football.com/leagues/1.png"
"flag" => null
"standings" => 1
"is_current" => 1
]
1 => array:13 [▼
"league_id" => 2
"name" => "Premier League"
"type" => "League"
"country" => "England"
"country_code" => "GB"
"season" => 2018
"season_start" => "2018-08-10"
"season_end" => "2019-05-12"
"logo" => "https://media.api-football.com/leagues/2.png"
"flag" => "https://media.api-football.com/flags/gb.svg"
"standings" => 1
"is_current" => 0
]
.......
but until now,with the following code:
$request = json_decode($request->getBody()->getContents(), true);
foreach ($request as $array=>$val) {
foreach ($val['leagues'] as $id) {
dd($id);
}
}
the only thing that i can get is the first array only and not the rest:
array:13 [▼
"league_id" => 1
"name" => "World Cup"
"type" => "Cup"
"country" => "World"
"country_code" => null
"season" => 2018
"season_start" => "2018-06-14"
"season_end" => "2018-07-15"
"logo" => "https://media.api-football.com/leagues/1.png"
"flag" => null
"standings" => 1
"is_current" => 1
]
any help?
The dd() function you are calling is killing the execution of your script on your first iteration.
From the Laravel Docs:
The dd function dumps the given variables and ends execution of the script.
If you do not want to halt the execution of your script, use the dump function instead.
Just iterate over it like so:
$request = json_decode($request->getBody()->getContents(), true);
foreach ($request['leagues'] as $id=>$league) {
print_r(compact('id', 'league')); // To see the id and value array
}
Hope this helps,

Display results of second array in nested array php dump

I have the following code:
public function canceledReasons()
{
$searchs = Zendesk::search()->find('type:ticket tags:cancel');
$searchs = json_decode(json_encode($searchs),true);
foreach ($searchs as $search) {
dump($search);
}
}
It returns an array that has some nested arrays in them I'm trying to display the second array in "tags" if it exists. There might be more than one array in there so it might be good to display them all.
Results
array:100 [▼
0 => array:36 [▼
"url" => "https://example/api/v2/tickets/example.json"
"id" => example
"external_id" => null
"via" => array:2 [ …2]
"created_at" => "2019-08-28T02:05:22Z"
"updated_at" => "2019-08-29T23:00:54Z"
"type" => null
"subject" => "example"
"raw_subject" => "example"
"description" => """
From: example\n
Phone: \n
Location: example\n
URL: https://example.zendesk.com/hc/en-us/categories/#####-Account-Billing\n
Department: \n
\n
Hi,\n
please cancel ▶
\n
Best,\n
Vinay\n
\n
----\n
Zopim\n
https://www.example.com
"""
"priority" => null
"status" => "open"
"recipient" => "example"
"requester_id" => example
"submitter_id" => example
"assignee_id" => example
"organization_id" => null
"group_id" => example
"collaborator_ids" => []
"follower_ids" => []
"email_cc_ids" => []
"forum_topic_id" => null
"problem_id" => null
"has_incidents" => false
"is_public" => true
"due_at" => null
"tags" => array:2 [ …2]
"custom_fields" => array:2 [ …2]
"satisfaction_rating" => null
"sharing_agreement_ids" => []
"fields" => array:2 [ …2]
"followup_ids" => []
"brand_id" => example
"allow_channelback" => false
"allow_attachments" => true
"result_type" => "ticket"
]
1 => array:36 [▶]
2 => array:36 [▶]
3 => array:36 [▶]
4 => array:36 [▶]
When I try
dump($search['tags']);
It returns Undefined index: tags
Just trying to get the results of the 'tags' arrays.
Thanks for the help.
try this...
public function canceledReasons()
{
$searchs = Zendesk::search()->find('type:ticket tags:cancel');
$searchs = json_decode(json_encode($searchs),true);
foreach ($searchs as $search) {
dump($search[0]['tags']);
//or to get all tags array value
foreach ($search[0]['tags'] as $tag) {
dump($tag);
}
}
}
```

Php add a key value to associative array in foreach loop

I am getting json data from an api endpoint, I would like to add a key value to an array that I get. This is my function:
$magazines = Magazine::all();
foreach ($magazines as $magazine) {
$result = file_get_contents('http://customer.pages.com/?customer=' . $magazine->visio_link_prefix . '&action=latest');
$issues[] = json_decode($result, true);
}
foreach ($issues as $issue) {
Issue::create([
''
'title' => $issue['papers'][0]['title'],
'date' => $issue['papers'][0]['date'],
'foldername' => $issue['papers'][0]['foldername'],
'thumb' => $issue['papers'][0]['thumb'],
'thumbmedium' => $issue['papers'][0]['thumbmedium'],
]);
}
The array that I get from the endpoint looks like this:
array:24 [▼
0 => array:1 [▼
"papers" => array:1 [▼
0 => array:11 [▼
"title" => "News- 2014-10-22"
"date" => "2014-10-22"
"expires" => ""
"catalog" => 24
"foldername" => "News"
"folder" => 4965
"pages" => 132
"sectionstarts" => "1"
"sectioncount" => 1
"thumb" => "www.customer.pages.com/news/24/teasers/small.jpg"
"thumb_medium" => "www.customer.pages.com/news/24/teasers/medium.jpg"
]
]
]
1 => array:1 [▶]
2 => array:1 [▶]
3 => array:1 [▶]
4 => array:1 [▶]
5 => array:1 [▶]
6 => array:1 [▶]
7 => array:1 [▶]
8 => array:1 [▶]
9 => array:1 [▶]
10 => array:1 [▶]
11 => array:1 [▶]
12 => array:1 [▶]
13 => array:1 [▶]
14 => array:1 [▶]
15 => array:1 [▶]
16 => array:1 [▶]
17 => array:1 [▶]
18 => array:1 [▶]
19 => array:1 [▶]
20 => array:1 [▶]
21 => array:1 [▶]
22 => array:1 [▶]
23 => array:1 [▶]
]
So, in my foreach loop I would like to add a key value pair 'magazineId' => $magazine->id to each of the above 'papers' arrays. So that later I can use $issue['papers'][0]['magazineId'] to get the value of the $magazine->id. Not sure how to do that?
This correction to yoiur code should do the trick:
foreach ($magazines as $magazine) {
$result = file_get_contents('http://customer.pages.com/?customer=' . $magazine->visio_link_prefix . '&action=latest');
$issue = json_decode($result, true);
foreach($issue['papers'] as $paperKey => $paper) {
$issue['papers'][$paperKey]['magazineId'] = $magazine->id;
}
$issues[] = $issue;
}
foreach ($issues as $issue) {
Issue::create([
'magazineId' => $issue['papers'][0]['magazineId'],
'title' => $issue['papers'][0]['title'],
'date' => $issue['papers'][0]['date'],
'foldername' => $issue['papers'][0]['foldername'],
'thumb' => $issue['papers'][0]['thumb'],
'thumbmedium' => $issue['papers'][0]['thumbmedium'],
]);
}
And the second version where you have only one magazineId key for a single issue:
foreach ($magazines as $magazine) {
$result = file_get_contents('http://customer.pages.com/?customer=' . $magazine->visio_link_prefix . '&action=latest');
$issue = json_decode($result, true);
$issue['magazineId'] = $magazine->id;
$issues[] = $issue;
}
Could you please try code below? In first foreach I added an array to $issue.
$magazines = Magazine::all();
foreach ($magazines as $magazine) {
$result = file_get_contents('http://customer.pages.com/?customer=' . $magazine->visio_link_prefix . '&action=latest');
$issues[] = array('magazine_id' => $magazine->id, 'result' => json_decode($result, true);
}
foreach ($issues as $issue) {
Issue::create([
'magazine_id' => $issue['magazine_id'],
'title' => $issue['result']['papers'][0]['title'],
'date' => $issue['result']['papers'][0]['date'],
'foldername' => $issue['result']['papers'][0]['foldername'],
'thumb' => $issue['result']['papers'][0]['thumb'],
'thumbmedium' => $issue['result']['papers'][0]['thumbmedium'],
]);
}

Get the values from a nested JSON array in PHP Laravel

So I have a piece of code that I have been fighting with for a while now.
Here is the code that I have
<?php
namespace App\Http\Controllers;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use App\Requests\SearchRequest;
use Vinelab\Http\Client as HttpClient;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class SearchResults extends Controller
{
public function index()
{
return view('results.search-results');
}
public function store(Requests\SearchRequest $request)
{
$searchPhrase = $request->input('search');
$client = new HttpClient;
$response = $client->get('https://www.reddit.com/search.json?q='. urldecode($searchPhrase) .'');
$response = collect($response->json());
$responseDecode = json_decode($response, true);
$SearchResultsArray = $responseDecode;
dd($SearchResultsArray);
}
}
And this returns a nested array that looks like this
array:2 [▼
"kind" => "Listing"
"data" => array:5 [▼
"facets" => []
"modhash" => ""
"children" => array:25 [▼
0 => array:2 [▼
"kind" => "t3"
"data" => array:52 [▶]
]
1 => array:2 [▶]
2 => array:2 [▶]
3 => array:2 [▶]
4 => array:2 [▶]
5 => array:2 [▶]
6 => array:2 [▶]
]
"after" => "t3_38lgh9"
"before" => null
]
]
I am trying to access the title attribute that is inside each of these
1 => array:2 [▶]
2 => array:2 [▶]
3 => array:2 [▶]
4 => array:2 [▶]
5 => array:2 [▶]
6 => array:2 [▶]
7 => array:2 [▶]
I want to parse them to an array that I can send to a Laravel View.
Every time I try to acccess this I get undefined index or offset and I am at a loss as to how to go about this.
Can anybody assist me in finding a solution to this problem?
Edit ---------------------
I am now using this and it is working perfectly
$allData=[];
$counter = 1;
foreach ($posts as $post) {
//foreach post get the data and store it in a database
$allData[$counter]['title']= $post['data']['title'];
$sentiment = SentimentAnalysis::decision($allData[$counter]['title']);
$allData[$counter]['created']= $post['data']['created'];
RedditPosts::create([
'title' => $allData[$counter]['title'],
'created' => date($allData[$counter]['created']),
'sentiment' => $sentiment,
'search_identifier' => $search_id,
'search_phrase' => $searchPhrase
]);
$counter ++;
}
Basically you would need three foreach in your case to achieve the nested arrays like this
foreach($SearchResultsArray as $ThreeLevelArray){
foreach($ThreeLevelArray as $TwoLevelArray) {
foreach($TwoLevelArray as $OneevelArray) {
//your here son :)
}
}
}
$allData=[];
$counter = 1;
foreach ($posts as $post) {
//foreach post get the data and store it in a database
$allData[$counter]['title']= $post['data']['title'];
$sentiment = SentimentAnalysis::decision($allData[$counter]['title']);
$allData[$counter]['created']= $post['data']['created'];
RedditPosts::create([
'title' => $allData[$counter]['title'],
'created' => date($allData[$counter]['created']),
'sentiment' => $sentiment,
'search_identifier' => $search_id,
'search_phrase' => $searchPhrase
]);
$counter ++;
}

Categories