Illegal string offset 'name' php - Many Array into 1 Array - php

With the help of variable categories i have this array in which all the arrays are without key/default index , because of this when i do $categories as $category in foreach and when i echo $category['name'] it gives illegal sting offet.
using laravel blade
What can be the possible solution for this or should i validate array first?

The above code is in JSON format, convert to array first
for example
$ex = {
'result':"success",
'categories':[{
//your rest of the code
}]
}
$data = json_decode($ex, TRUE);
//next use for each
foreach($data as $key => $value)
{
//rest of your logic
}

I think this is your situation, and in my opinion, you are using the wrong variable to decode let me take your image as an example here.
<?php
$ex = [
'result' => 'success',
'categories' => [
[
'id'=>1,
'name'=>'cat1',
],
[
'id'=>2,
'name'=>'cat21',
],
[
'id'=>3,
'name'=>'cat31',
],
]
];
echo "<pre>";
$res = json_encode($ex);
print_r(json_decode($res));
in this example, I just showed you that I have done json_encode and json_decode easily without any issue and the output of JSON is same as your example image.
Thank You!

Related

Looping through nested arrays in php 7.2

I am trying to access values in a nested array that I send to my API but when do something like $data['inputs']{0} it only gives me back the first letter of the key when what I want is the whole value of the value and not the key but if I try something like $data['inputs']['type'] it gives me an offset error I ament sure how to correctly access the values the way I need to
public function saveEdit(Request $request)
{
try {
$unsanitizedData = $request->all();
$data = [];
$fid = $unsanitizedData['formId'];
$data['form_name'] = json_encode($unsanitizedData['cred']['name']);
$data['org'] = json_encode($unsanitizedData['cred']['organization']);
$data['updated_by'] = json_encode($unsanitizedData['updatedBy']);
$data['user_id'] = json_encode($unsanitizedData['id']);
$data['activated'] = json_encode($unsanitizedData['cred']['activated']);
$data['inputs'] = json_encode($unsanitizedData['cred']['inputs']);
$pattren = array("[","]","'",'"',"/","\\");
$data = str_replace($pattren,'', $data);
foreach ($unsanitizedData as $st) {
admin_form::where('id', $fid)->update([
'form_name' => $data['form_name'],
'org' => $data['org'],
'updated_by' => $data['updated_by'],
'user_id' => $data['user_id'],
'activated' => $data['activated']
]);
foreach ($data['inputs'] as $input) {
admin_form_fields::where('form_id', $fid)->update([
'type' => $input,
'name' => $input
]);
}
}
$res['status'] = true;
$res['message'] = 'Success';
return response($res, 200);
} catch (\Illuminate\Database\QueryException $ex) {
$res['status'] = false;
$res['message'] = $ex->getMessage();
return response($res, 500);
}
}
I thought if I use a foreach loop inside another foreach loop it would work because its a nested array so loop through the main one and then through the nested one but that did also not work
Data Structure when I do a data dump:
array:6 [
"form_name" => "Testname",
"org" => "TestOrg",
"updated_by" => "test",
"user_id" => "29",
"activated" => "false",
"inputs" => "{type:number,name:Phone},{type:input,name:Name},{type:input,name:Address},{type:email,name:Email}"
]
In your case, $data['inputs'] is a JSON encoded string from which you have removed the [ and ] characters so when you try to access its first element it's the first char (since strings are kind of arrays of strings in PHP, they are really array of strings in C).
The problem is that you call json_encode() in the first place. If it's how you sanitize input, you're doing it wrong. Since you're using an ORM, there's no real need to manually sanitize the input. Just keep your input as sent by the client and perform all your operations then use them unsanitized in the QueryBuilder
As far as I can see, you just need to use json_decode($data['inputs']) since your array is in fact just a string :)

Generate php array definition from JSON

My question is a bit different to most like this, I basically want to do the opposite to this question from Haluk.
So I have a JSON string:
{
"main":
{
"title": "QuickPub",
"defaultRole": "BU"
},
"roles":
{
"TU":
{
"name": "testUser",
"code": "TU"
}
}
}
and I want to be able to generate a string containing a php array definition from it:
<?php
return [
"main" =>
[
"title" => "QuickPub",
"defaultRole" => "BU"
],
"roles" =>
[
"TU" =>
[
"name" => "testUser",
"code" => "TU"
]
]
];
?>
EDIT:
I have tried json_decode() but this produces a variable, I need a string that I can put in a php file that will reproduce this without using php_decode.
I think this will solve your problem. First of all convert your json string to an array using json_decode($string,1); then convert that array to string representation using print_r($array,1); this will return your result as array string representation.
For example:
$json='{}' // its a demo
$array= json_decode($json,1); // an array
$result = print_r($array,1);
echo $result;
This is an adaptation of Being Sunny's answer, but using the var_export() function rather than print_r.
As described here by phihad
var_export prints valid php code. Useful if you calculated some values and want the results as a constant in another script
the script:
$json = '{"main":{"title": "QuickPub","defaultRole": "BU"},"roles":{"TU":{"name": "testUser","code": "TU"}}}';
$array = json_decode($json, 1);
$result = var_export($array, 1);
echo $result;
produces:
array(
'main' => array(
'title' => 'QuickPub',
'defaultRole' => 'BU',
),
'roles' => array(
'TU' => array(
'name' => 'testUser',
'code' => 'TU',
),
),
)
This can be achieved using this code:
$output = 'return ' . rtrim(preg_replace(['/{/', '/}/', '/:/'], ['[', ']', ' =>'], $json)) . ';';
this replaces { with [, } with ], and : with =>, trims any whitespace from the end, appends a ; and prepends a return statement.
this produces the output requested in the question bar the open and closing php tags.

Laravel 5.3 - Storing and retrieving multiple key-value pairs in session

I'm using Laravel 5.3 to build a quiz and I would like to store the results in the session. So, each time the user submits a quiz response, the result is added to the session array.
For example I would like to store the answers something like this:
answers = [q1=correct, q2=correct, q3=incorrect,...]
Then at the end pf the quiz, I want to be able to retrieve and list the results and perhaps style the correct answers green and the wring answers red.
Could anybody provide any guidance on how to achieve this?
The simplest solution would be to store the response as a JSON encoded string.
session([
'answers' => json_encode([
[
'q1'=>'correct',
'q2'=>'correct',
'q3'=>'incorrect'
]
])
]);
There are more elegant solutions but would do the trick.
You can simply use the session() helper function for this
For Answers
public function answer($questionId)
{
$question = Question::findOrFail($id);
if(!session()->has('question.answers')) {
session()->put('question.answers', [[ //Notice the 2 brackets. Y? Checkout below.
$question->id => request()->get('answer')
]]);
} else {
session()->push('question.answers', [ //pushing into array
$question->id => request()->get('answer')
]);
}
}
At the end of the quiz
public function end($question)
{
$answers = session()->get('question.answers');
// Output: [ [1 => 'answer1'], [2 => 'answer2'] ]
$answers = array_flatten($answers);
// Output: [ 1 => 'answer1', 2 => 'answer2' ]
}

Iterate values of Associative array if it has one object or more

My Problem is, I have set of arrays
$people =[{name:'Alan', hasChild:true},
{name:'Alice', hasDetail:true}];
And other one is
$people =[{name:'Alan', hasChild:true}];
I need to print all elements.
I have tried in below way
for($i=0; $i<count($people); $i++){
echo $people[$i]['name'];
}
The first one is working fine. But second one show an error like this
Notice: Undefined offset: 0 in /opt/lampp/htdocs/vp/pending_users.php on line 320
Why it happen? How do i overcome this issue
This is very basic stuff. You should read a few beginner's tutorials.
You can loop the array using a foreach loop, like this:
$people = [
[
'name' => 'Alan',
'hasChild' => true
],
[
'name' => 'Alice',
'hasChild' => true
]
];
foreach ($people as $person) {
echo $person['name'] . "\n";
}

Creating a JSON object from multidimensional array stored as string

I'm trying to generate a JSON object using PHP to be passed to the client using data that is already stored in MySQL database.
The database contains a list of multipolygon coordinates like below in a single text field:
[
[
[
[
104.39209000000005,
-4.850154
],
[
108.17138687500005,
-3.721745195827911
],
[
112.12646500000005,
-1.274309
],
[
103.02978499999995,
-3.579213
]
]
]
]
When I try to generate a JSON object using json_encode I get the following:
{
"coordinates": "[[[[104.39209000000005,-4.850154],[108.17138687500005,-3.721745195827911],[112.12646500000005,-1.274309],[103.02978499999995,-3.579213]]]]"
}
And because of the quotes around the coordinates themselves, they are not recognised as JSON object by JavaScript.
I've tried to explode the coordinate string and then put it back together manually but it still needs a lot of hacks to get it working.
Any help in getting this to output as a an actual JSON object in PHP would be much appreciated.
I'm trying to get to this:
{
"coordinates": [
[
[
[
104.39209000000005,
-4.850154
],
[
108.17138687500005,
-3.721745195827911
],
[
112.12646500000005,
-1.274309
],
[
103.02978499999995,
-3.579213
]
]
]
]
}
It's pretty jerry-rigged, but you could do this:
$string = json_encode( $database_value ); // same as you're using now
$string = str_replace( '"', '', $string ); // get rid of the quotes
// wrap them back around 'coordinates'
$string = str_replace( 'coordinates', '"coordinates"', $string );
Simply use json_decode before json_encode, like this:
// This comes from the database, of course
$coords = '[[[[104.39209000000005,-4.850154],[108.17138687500005,-3.721745195827911],[112.12646500000005,-1.274309],[103.02978499999995,-3.579213]]]]';
echo json_encode(array(
'coordinates' => json_decode($coords)
));
This will output nested arrays exactly as you desire:
{"coordinates":[[[[104.39209,-4.850154],[108.171386875,-3.7217451958279],[112.126465,-1.274309],[103.029785,-3.579213]]]]}

Categories