Display results of second array in nested array php dump - php

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);
}
}
}
```

Related

Foreach - Array inside another array - Returns only 1 index - I need to return all values ​of key_number:

I want to get from my answer only the values ​​of the key_number; even though I return the foreach inside another foreach, it returns only one index and not the two values ​​of the request.
Controller
foreach (array($request['key_number']) as $notaFiscal) {
foreach($notaFiscal as $notas) {
dd($notas);
}
// $moviment->document()->create($notasFiscais);
}
Request
dd($request);
+request: Symfony\Component\HttpFoundation\InputBag {#1535
#parameters: array:8 [
"type" => null
"people_id" => 5
"company_id" => 1
"vehicle_id" => 2
"department_id" => "12179"
"document_id" => null
"document_type_id" => 1
"key_number" => array:2 [
0 => array:2 [
"title" => "New Title"
"key_number" => "444444"
]
1 => array:2 [
"title" => "New Title"
"key_number" => "555555"
]
]
]
}
Request foreach index key_number
array:2 [ // app\Http\Controllers\MovimentController.php:50
0 => array:2 [
"title" => "New Title"
"key_number" => "444444"
]
1 => array:2 [
"title" => "New Title"
"key_number" => "555555"
]
]
foreach inside foreach return only one index
array:2 [ // app\Http\Controllers\MovimentController.php:51
"title" => "New Title"
"key_number" => "444444"
]
Return all index key_number, not one index.

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"]));

Convert Collection to Array with I=ID in Laravel

I am beginner php developer.
I have small problem with my array. I use in my project Laravel 7
I have this code:
$items = collect($discount->products->toArray());
It's result me:
Illuminate\Support\Collection {#1783 ▼
#items: array:2 [▼
0 => array:17 [▼
"id" => 1
"product_category_id" => 5
"image_id" => null
"vat_type_id" => 1
"name" => "Produkt 1"
"slug" => "produkt-1"
"lead" => "<p>fewferfer</p>"
"description" => "<p> </p>"
"price" => "123.00"
"loyalty_program_points_price" => 2
"min_student_level" => null
"marked_as_available_at" => "2020-09-30T11:45:51.000000Z"
"deactivated_at" => null
"created_at" => "2020-09-30T11:45:23.000000Z"
"updated_at" => "2020-09-30T11:45:51.000000Z"
"deleted_at" => null
"pivot" => array:3 [▶]
]
1 => array:17 [▼
"id" => 2
"product_category_id" => 5
"image_id" => null
"vat_type_id" => 1
"name" => "Produkt 2"
"slug" => "produkt-2"
"lead" => "<p> </p>"
"description" => "<p>fergfer</p>"
"price" => "21.00"
"loyalty_program_points_price" => 3
"min_student_level" => null
"marked_as_available_at" => "2020-09-30T11:45:38.000000Z"
"deactivated_at" => null
"created_at" => "2020-09-30T11:45:38.000000Z"
"updated_at" => "2020-09-30T11:45:38.000000Z"
"deleted_at" => null
"pivot" => array:3 [▶]
]
]
}
I need convert it to this result:
Array{
1 => 1 (id)
2 => (id)
}
How can I make it?
I need array with only id values
Collections have the pluck method, which allows you to grab all the values of a specific key. To get all of the ids, you'd just need to do
$ids = $items->pluck('id')->all();
If you want them to have the same key as the id as well, pass that as the second parameter
$ids = $items->pluck('id', 'id')->all();
As a note, if products is a relation, then it's already a collection. You do not need to convert it to an array, then back to a collection:
$product_ids = $discount->products->pluck('id')->all();

Find the key and return true in a deeply nested set of arrays php

So there are tons of questions like this, but I haven't found an answer the suits my desired outcome.
consider the following array:
array:13 [
"Peripheral Neuropathy" => array:3 [
"name" => "peripheral_neuropathy"
"value" => array:1 [
0 => "yes"
]
"dependencies" => array:5 [
"neuropathy_staging_fap" => array:1 [
0 => "2"
]
"neuropathy_staging_pnd" => array:1 [
0 => "II"
]
"specify_type" => array:1 [
0 => "Sensory"
]
"autonomic" => array:1 [
0 => "yes"
]
"sensory_fiber_size" => array:1 [
0 => "Small"
]
]
]
"Neuropathic pain" => array:3 [
"name" => "neuropathic_pain"
"value" => array:1 [
0 => "yes"
]
"dependencies" => []
]
"Functional Motor Assessment" => array:3 [
"name" => "functional_motor_assessment"
"value" => array:1 [
0 => "Yes"
]
"dependencies" => array:3 [
"functional_motor_assessment_test_name" => "sample"
"functional_motor_assessment_test_score" => "10"
"functional_motor_assessment_date" => "2020-02-11"
]
]
"Assessment name" => array:3 [
"name" => "functional_motor_assessment_test_name"
"value" => "sample"
"dependencies" => []
]
"Assessment Score" => array:3 [
"name" => "functional_motor_assessment_test_score"
"value" => "10"
"dependencies" => []
]
"Assessment Date" => array:3 [
"name" => "functional_motor_assessment_date"
"value" => "2020-02-11"
"dependencies" => []
]
"Carpal Tunnel Syndrome" => array:3 [
"name" => "carpal_tunnel_syndrome"
"value" => array:1 [
0 => "yes"
]
"dependencies" => []
]
"EMG" => array:3 [
"name" => "emg"
"value" => array:1 [
0 => "yes"
]
"dependencies" => array:5 [
"emg_type" => array:1 [
0 => "Median"
]
"median_amplitude" => "10"
"median_CV" => "10"
"median_tml" => "10"
"median_size" => array:1 [
0 => "7cm"
]
]
]
"EMG Type" => array:3 [
"name" => "emg_type"
"value" => array:1 [
0 => "Median"
]
"dependencies" => array:4 [
"median_amplitude" => "10"
"median_CV" => "10"
"median_tml" => "10"
"median_size" => array:1 [
0 => "7cm"
]
]
]
"Amplitude" => array:3 [
"name" => "median_amplitude"
"value" => "10"
"dependencies" => []
]
"CV" => array:3 [
"name" => "median_CV"
"value" => "10"
"dependencies" => []
]
"TML" => array:3 [
"name" => "median_tml"
"value" => "10"
"dependencies" => []
]
"Size" => array:3 [
"name" => "median_size"
"value" => array:1 [
0 => "7cm"
]
"dependencies" => []
]
]
As we can see there are duplicates, for example look at: Functional Motor Assessment under dependencies - this is correct, but directly under Functional Motor Assessment is Assessment name with the name functional_motor_assessment_test_name.
This is the duplicate. This specific array, Assessment name should not exist because the name already exists in Functional Motor Assessment's dependencies array.
So I thought, I will write the following function:
protected function alreadyExists(array $values, string $fieldName) {
if (empty($values)) {
return false;
}
foreach ($values as $key => $value) {
foreach ($value as $k => $v) {
if ($k === 'dependencies' && !empty($value[$k])) {
return array_key_exists($fieldName, $value[$k]);
}
}
}
return false;
}
where $value is the above array and in this case $fieldName would be (for example) functional_motor_assessment_test_name.
The idea here is that this should walk through the array looking for any key that matches: functional_motor_assessment_test_name and return true if found or false if not (false if the (above) array is empty).
Theres a couple rules:
Return false if the value array is empty, because obviously it wont exist.
Return false if never found
Skip the check if the the dependencies array is empty (it can be empty sometimes).
This is where it should move on to the next array, so if not found in Peripheral Neuropathy move on to Neuropathic pain and so on ...
I think this function has to be recursive, but I am not sure where to put the recursive aspect, to say: well I didn't find it in Peripheral Neuropathy, let's check Neuropathic pain and so on and so forth. Until it is either found or not.
I tried array_walk_recursive, but as I expected while reading the docs, there is no way to break from that kind of function - so I thought, this function I have is on the right track, I just need to make it recursive.
Ideas?
There's no need to loop over the second level arrays, just get the dependencies element directly with indexing.
public function alreadyFound(array $values, string $fieldName) {
foreach ($values as $item) {
if (!empty($item['dependencies']) && array_key_exists($fieldName, $item['dependencies'])) {
return true;
}
return false;
}
If there can be dependencies nested within dependencies, you do need a recursive solution.
protected function alreadyExists(array $values, string $fieldName) {
if (array_key_exists($fieldName, $values)) {
return true;
}
foreach ($values as $item) {
if (!empty($item['dependencies']) && $this->alreadyExists($item['dependencies'], $fieldName) {
return true;
}
}
return false;
}

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,

Categories