Array to string conversion with array_walk in PHP - php

I am tried to add the same string to every array value.
I tried to use array_walk() like I read it on this answer.
But I get: Notice: Array to string conversion
I have also tried to use array_map(), but I get same error notice.
working code
if ($voice->getValue() === Voice::Passive) {
array_walk($aller_form, function(&$value, $key) { $value .= ' être'; });
$aller_form = [
Mood::Indicatif => [
Tense::Futur_compose => [
Person::FirstPersonSingular => 'vais être',
Person::SecondPersonSingular => 'vas être',
Person::ThirdPersonSingular => 'va être',
Person::FirstPersonPlural => 'allons être',
Person::SecondPersonPlural => 'allez être',
Person::ThirdPersonPlural => 'vont être'
]
]
];
}
return $aller_form[$mood->getValue()][$tense->getValue()][$person->getValue()];
not working code
if ($voice->getValue() === Voice::Passive) {
array_walk($aller_form, function(&$value, $key) { $value .= ' être'; });
}
return $aller_form[$mood->getValue()][$tense->getValue()][$person->getValue()];
EDIT:
The complete error log:
Notice: Array to string conversion in on line 2
Warning: Illegal string offset 'futur_compose' on line 4
Warning: Illegal string offset 'firstPersonSingular' on line 4
(I see 6 times this three error lines for every Person once)

Related

Unable to fetch data from Laravel Eloquent Relationships

i wanted access the value of content_type_id .i tried like $courseChapters['chapter_content']['content_type_id'] , $courseChapters['content_type_id'] , $courseChapters[0]['content_type_id'] & $courseChapters['chapterContent']['content_type_id'].All these shows the error ErrorException: Undefined index: content_type_id . I also tried everything in the foreach loop i've commented below. Nothing works. Can someone tell me how to fix this?
/*foreach($courseChapters as $key){
// $contentTypeId=$key->first(); //Call to a member function first() on int
// $contentTypeId=$key->first()->chapter_content; //Call to a member function first() on int
// $contentTypeId=$key['chapter_content']['content_type_id']; //error - Illegal string offset
// $contentTypeId=$key[0]['content_type_id']; ////error - Illegal string offset
// $contentTypeId=$key['content_type_id']; //error - Illegal string offset 'content_type_id'
}*/
$courseChapters = courseChapter::with(['chapterContent' => function ($q) use ($id) { $q->where('course_chapter_id', $id)->select('course_chapter_id','file_id','content_type_id');}])
->select('id','courseId', 'chapter_title', 'isExam', 'points')
->get()->toArray()[0];
Heading ## dd($courseChapters); shows array like given below:
array:6 [
"id" => 4
"courseId" => 24
"chapter_title" => "chapter1"
"isExam" => false
"points" => 8
"chapter_content" => array:1 [
0 => array:3 [
"course_chapter_id" => 4
"file_id" => 1
"content_type_id" => 1
]
]
]
Like this to access the first
echo $courseChapters['chapter_content'][0]['content_type_id'];
or like this to access all of them
foreach ($courseChapters['chapter_content'] as $chapter) {
echo $chapter['content_type_id'];
}

Loop events, grab data from specific keys, add to new array - PHP [duplicate]

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 3 years ago.
I am trying to loop through these array items and grab data from just the url items, adding all that collected data to a new array.
Steps I am trying to achieve:
1. Loop through the $event['lineups'] (4 items).
2. Loop through the data inside the event (6 items each)
3. Grab the following from each:
facebook_page_url, instagram_page_url, official_website_url
array (size=4)
0 =>
array (size=6)
'id' => string '22007301-f49f-442d-b93f-4c7ce5cbc8de' (length=36)
'name' => string 'MC Bassman' (length=10)
'facebook_page_url' => string 'https://www.facebook.com/bassmansdc/' (length=36)
'instagram_page_url' => string 'https://www.instagram.com/mcbassman_sdc/' (length=40)
'official_website_url' => string '' (length=0)
'position' => int 1
1 =>
array (size=6)
'id' => string 'f4c41b6f-33a1-4da0-b7fa-ffdfbd84724d' (length=36)
'name' => string 'Indika' (length=6)
'facebook_page_url' => string 'https://www.facebook.com/INDIKAMCR/' (length=35)
'instagram_page_url' => string 'https://www.instagram.com/indikamcr/' (length=36)
'official_website_url' => null
'position' => int 2
My attempt and code:
Set which keys we need to grab data from:
$default_keys = [
'facebook_page_url',
'instagram_page_url',
'official_website_url',
];
Create a new array to add data to:
$performer_urls = [];
Loop through each $event['lineups'] item in array: array (size=4)
foreach( $event['lineups'] as $lineups ) {
Loop through each value in array: array (size=6)
foreach( $lineups as $lineup ) {
Check if data exists, if so, update the $performer_urls array with a key and data.
if ( isset( $lineup[ $key ] ) && ! empty( $lineup[ $key ] ) ) {
$performer_urls[$key] = $event['lineups'][ $key ];
}
Full code so far:
$default_keys = [
'facebook_page_url',
'instagram_page_url',
'official_website_url',
];
$performer_urls = [];
foreach( $event['lineups'] as $lineups ) {
foreach( $lineups as $lineup ) {
// Example: $contact_details['address_line_1']
if ( isset( $lineup[ $key ] ) && ! empty( $lineup[ $key ] ) ) {
// Update array (example): $address['address_line_1'] = $contact_details['address_line_1']
$performer_urls[$key] = $event['lineups'][ $key ];
}
}
}
var_dump($performer_urls);
Notice: Undefined variable: key in
The errors I am getting now are referring to the undefined $key variable being used but hopefully you can see what I am trying to achieve here and almost there?
I believe I came out with a solution, I got your idea but I'm afraid you have some issues in your code.
I've just refactored them, and the most important, I didn't get it how exactly are you going to populate your new $performer_urls array without overwriting keys, that's why I chose to incremental keys just using [ ] syntax.
First things first, yes PHP is right complaining about your $key undefined variable :-) example:
Then I refactored the wrong parts (as I got it), here it comes the full code:
<?php
$event['lineups'] = [
[
'id' => '22007301-f49f-442d-b93f-4c7ce5cbc8de',
'name' => 'MC Bassman',
'facebook_page_url' => 'https://www.facebook.com/bassmansdc/',
'instagram_page_url' => 'https://www.instagram.com/mcbassman_sdc/',
'official_website_url' => '',
'position' => 1,
],
[
'id' => 'f4c41b6f-33a1-4da0-b7fa-ffdfbd84724d',
'name' => 'Indika',
'facebook_page_url' => 'https://www.facebook.com/INDIKAMCR/',
'instagram_page_url' => 'https://www.instagram.com/indikamcr/',
'official_website_url' => null,
'position' => 2,
],
];
$default_keys = [
'facebook_page_url',
'instagram_page_url',
'official_website_url',
];
$performer_urls = [];
foreach ($event['lineups'] as $lineups) {
foreach ($lineups as $key => $value) {
if (in_array($key, $default_keys) && !empty($value)) {
$performer_urls[] = $value;
}
}
}
var_dump($performer_urls);
I've got this:
array(4) {
[0] =>
string(36) "https://www.facebook.com/bassmansdc/"
[1] =>
string(40) "https://www.instagram.com/mcbassman_sdc/"
[2] =>
string(35) "https://www.facebook.com/INDIKAMCR/"
[3] =>
string(36) "https://www.instagram.com/indikamcr/"
}

Php key is undefined, but there is key

I am making my own array from another one, using email field as key value. If there is more results with same email I am amking array_push to existing key.
I am getting always data in my array (with email) and here is the example
Input data
Example data
$saved_data = [
0 => ['custom_product_email' => 'test#test.com',...],
1 => ['custom_product_email' => 'test#test.com',...],
2 => ['custom_product_email' => 'bla#test.com',...],
3 => ['custom_product_email' => 'bla#test.com',...],
...
];
Code
$data = [];
foreach ($saved_data as $products) {
$curVal = $data[$products->custom_product_email];
if (!isset($curVal)) {
$data[$products->custom_product_email] = [];
}
array_push($data[$products->custom_product_email], $products);
}
Error
I am getting error Undefined index: test#test.com and if I debug my array, there is key with value of 'test#test.com', so key is defined (!)
so var $curVal key is undefined
Result
So the goal of foreach is to filter all objects in array with same email, here is the example:
$data = [
'test#test.com' => [
0 => {data},
1 => {data},
...
],
'bla#test.com' => [
0 => {data},
1 => {data},
...
],
];
this line $curVal = $data[$products->custom_product_email]; is useless and is the one provoking the error: you just initialized $data as an empty array, logically the index is undefined.
You should test directly if (!isset($data[$products->custom_product_email])) {
Then explanation: there is a fundamental difference between retreiving the value of an array's index which is undefined and the same code in an isset. The latter evaluating the existence of a variable, you can put inside something that doesn't exist (like an undefined array index access). But you can't store it in a variable before the test.
Did you not see the error message?
Parse error: syntax error, unexpected '{' in ..... from this code
$saved_data = [
0 => {'custom_product_email' => 'test#test.com',...},
1 => {'custom_product_email' => 'test#test.com',...},
2 => {'custom_product_email' => 'bla#test.com',...},
3 => {'custom_product_email' => 'bla#test.com',...},
...
];
Change the {} to [] to correctly generate the array.
$saved_data = [
0 => ['custom_product_email' => 'test#test.com',...],
1 => ['custom_product_email' => 'test#test.com',...],
2 => ['custom_product_email' => 'bla#test.com',...],
3 => ['custom_product_email' => 'bla#test.com',...],
...
];
Your next issue is in this code
$data = [];
foreach ($saved_data as $products) {
$curVal = $data[$products->custom_product_email];
// ^^^^^
$data is an empty array that you initialised 2 lines above, so it does not contain any keys or data!
Check, if $data[$products->custom_product_email] is already set in $data array
Try This code
$data = [];
foreach ($saved_data as $products) {
$curVal = isset($data[$products->custom_product_email]) ? $data[$products->custom_product_email] : null;
if (!isset($curVal)) {
$data[$products->custom_product_email] = [];
}
array_push($data[$products->custom_product_email], $products);
}

illegal string offset '#id' in test.php

Not sure if data issue or program issue, sometimes below program
show error message :
PHP Warning : "illegal string offset '#id' in test.php"
PHP Warning : "illegal string offset 'Order' in test.php"...
....
$ret1=curlDest($transaction_url);
$retval = $ret1["Response"]["TransactionList"]["#TotalCount"];
foreach ($ret1["Response"]["TransactionList"]["Transaction"] as $v)
{
$transaction_id = $v["#Id"];
$order_id = array();
$orderid_query_string = '';
foreach ($v["Order"] as $order)
{...
}
the data of #ret1 is below
Array
<
[#Id] => 120852760
[Order] = > Array
<
[#Id] => YM152222
>
>
The error said
illegal string offset '#id'
You should use a capitalized #Id instead.

php - Warning: Illegal string offset but vardump shows correct string offset [duplicate]

This question already has answers here:
Illegal String Offset within PDO For Each loop
(2 answers)
Closed 8 years ago.
After completing a SELECT query on a MySQL database and applying the fetchAssoc() method to the result, I am receiving warnings when attempting to access the results in a foreach loop. Here is the code:
$query=$subquery->execute()->fetchAssoc();
foreach($query as $result) {
if ($result['active'] == 'Y'){ // (this is line 703)
$page_id = $result['page_id']; // (this is line 704)
if (!$package_pages[$page_id] || $package_pages[$page_id] != $page_id) { // line 705
$pages[] = $page_id;
}
}
I inserted var_dump($query) to inspect the results of the query. Here is an example of the output:
array (size=3)
'page_name' => string 'Apts & Rentals' (length=14)
'page_id' => string '49' (length=2)
'active' => string 'Y' (length=1)
array (size=3)
'page_name' => string 'Homepage' (length=8)
'page_id' => string '1' (length=1)
'active' => string 'Y' (length=1)
There are 25 arrays output from var_dump($query)
And here is a sample of the warnings:
Warning: Illegal string offset 'active' in ads_load() (line 703 of ...
Warning: Illegal string offset 'page_id' in ads_load() (line 704 of ...
Notice: Undefined index: Y in ads_load() (line 705 of ...
Why are the offsets 'active', and 'page_id' being flagged as illegal?
Where is the "Notice: Undefined index: Y" coming from since it is not being used as an index on line 705?
I don't believe this is a duplicate of Illegal String Offset within PDO For Each loop. The issue was resolved when I realized the code given above was placed within another loop which gave the impression I was dealing with an array of arrays rather than a single array each time.
You're accessing them incorrectly - you've got an associative array and you're trying to loop through it as if it were an array of associative arrays. This is your dumped data structure:
$query = array(
'page_name' => 'Homepage',
'page_id' => '1',
'active' => 'Y' );
You can get the results directly from $query, i.e.:
$query=$subquery->execute()->fetchAssoc();
if ($query['active'] == 'Y')
$page_id = $query['page_id'];
// ... the rest of your code ...
}
You could iterate through the keys and values of $query, but since you are interested in particular values from the $query array, there isn't much point.

Categories