i was wondering how can i insert an array of data into one table by using of 2 array like this in laravel model
$attributes =array('title','description');
$options =array('test','blahblahblah');
the table would be like
title test
description blahblahblah
so far i reach to this
$values = array(
array($attributes => $options),
);
but it says
Illegal array key type array less
Arrays and objects can not be used as array keys.
any way i try has different error
but the most of the errors is illegal offset type
do you have any suggestion?
You can combine both arrays with array_combine. It will take an array for the keys and one array for the values.
$attributes = array('title', 'description');
$options = array('test', 'blahblahblah');
$values = array_combine($attributes, $options);
Result:
array:2 [▼
"title" => "test"
"description" => "blahblahblah"
]
You can try this:
First you have to combine array as following:
$tableFields = array('title', 'description');
$fieldValues = array('test', 'blahblahblah');
$newArr = array_combine($tableFields, $fieldValues);
Output :
array:2 [▼
"title" => "test"
"description" => "blahblahblah"
]
Then insert into table as following:
DB::table('table_name')->insert($newArr);
Related
I have in my database values with this form :
["email1#gmail.com","email2#gmail.com"]
I'm using laravel and I want to loop on this variable to get each element for example get the element : email1#gmail.com.
I tried the following code :
I have the following array :
$emails :
array:2 [▼
0 => "["email1#gmail.com","email2#gmail.com"]"
1 => "["email3#gmail.com","email4#gmail.com"]"
]
So I'm using the following code to get each element :
$var = array();
foreach ($emails as $key => $value) {
$var[] = $value;
}
I get the following result :
array:2 [▼
0 => "["email1#gmail.com","email2#gmail.com"]"
1 => "["email3#gmail.com","email4#gmail.com"]"
]
If you have any idea , please help
UPDATE
I have the following array :
array:2 [▼
0 => "["email1#gmail.com","email2#gmail.com"]"
1 => "["hajar.boualamia33#gmail.com","guernine.khadija#gmail.com"]"
]
And I did the following method :
$emailss = collect($emails)->flatten()->all();
dd($emailss);
I get the following result :
array:2 [▼
0 => "["email1#gmail.com","email2#gmail.com"]"
1 => "["hajar.boualamia33#gmail.com","guernine.khadija#gmail.com"]"
]
Update
Ha, tricky one. It seems that you have a PHP expression (an array) stored. So in order to extract the arrays, we need to evaluate them first.
Try this instead:
$elements = [
"['email1#gmail.com','email2#gmail.com']",
"['email3#gmail.com','email4#gmail.com']",
];
$emails = collect($elements)
->map(function ($element) {
return (eval("return \$element = " . $element . ';'));
})
->flatten()
->all();
Try this:
$elements = [
['email1#gmail.com','email2#gmail.com'],
['email3#gmail.com','email4#gmail.com'],
];
$emails = collect($elements)->flatten()->all();
This will get you:
=> [
"email1#gmail.com",
"email2#gmail.com",
"email3#gmail.com",
"email4#gmail.com",
]
Check this method on the docs.
I have a column in my db for saving a users' settings. This is what the data structure looks like:
{"email":{"subscriptions":"{\"Foo\":true,\"Bar\":false}"}}
I am using a vue toggle to change the status of each property (true/false). Everything seems to be working, however when I save, I am wiping out the structure and saving the updated values like this:
{\"Foo\":true,\"Bar\":false}"}
php
$user = auth()->user();
$array = json_decode($user->preferences['email']['subscriptions'], true);
dd($array);
The above gets me:
array:2 [
"Foo" => true
"Bar" => false
]
So far so good...
$preferences = array_merge($array, $request->all());
dd($preferences);
Gets me:
array:2 [
"Foo" => true
"Bar" => true
]
Great - the values are now picking up the values passed in from the axios request. Next up; update the user's data:
$user->update(compact('preferences'));
Now my data looks like this:
{"Foo":true,"Bar":true}
The values are no-longer nested; I've wiped out email and subscriptions.
I've tried this:
$user->update([$user->preferences['email']['subscriptions'] => json_encode($preferences)]);
But it doesn't seem to save the data. How can I use the $preferences variable to update the data - and keep the data nested correctly?
You can create an array with the structure you want the resulting json to have. So, for this json:
{
"email":{
"subscriptions":{
"Foo":true,
"Bar":false
}
}
}
you can create an array like this:
[
'email' => [
'subscriptions' => [
'Foo' => true,
'Bar' => false
]
]
]
an then, encode the entire structure:
json_encode([
'email' => [
'subscriptions' => [
'Foo' => true,
'Bar' => false
]
]
]);
So, in your code, as you already have the nested array in the $preferences variable, I think this should work:
$json_preferences = json_encode([
'email' => [
'subscriptions' => $preferences
]
]);
Then you can update the user 'preferences' attribute (just for example):
User::where('id', auth()->user()->id)->update(['preferences' => $json_preferences]);
or
$user = auth()->user();
$user->preferences = $json_preferences;
$user->save();
I am trying to pass the value to an api through json request.
$payload = json_encode( array("phones"=> "971xxxxxxx",
"emails"=> "fadfad#xyz.com",
"id"=> "1"
) );
How will i pass the below multi dimensional values to a json request like the above code?
{ "contactList": [ { "phones" : ["+91 9000000034"], "emails" : [fadfad#xyz.com], "id" : 1 }, { "phones" : ["+91 903-310-00-001"], "emails" : [krs#xyz.in], "id" : 2 } ] }
Store the data as nested / multidimensional arrays before passing it to json_encode.
$array = array();
$array["contactList"] = array(
array( "phones"=> "971xxxxxxx",
"emails"=> "fadfad#xyz.com",
"id"=> "1"
),
array( "phones"=> "+91 903-310-00-001",
"emails"=> "krs#xyz.in",
"id"=> "2"
)
);
$payload = json_encode($array);
echo $payload;
produces
{"contactList":[{"phones":"971xxxxxxx","emails":"fadfad#xyz.com","id":"1"},{"phones":"+91 903-310-00-001","emails":"krs#xyz.in","id":"2"}]}
If you need to hold values like the phone numbers inside an array, simply wrap them in an array.
$data = User::find()
->select('id, name')
->where(['status' => 'active'])
->orderBy('id DESC')
->asArray()
->all();
[
[0]=>[
id=>1
name="test"
]
[1]=>[
id=>2
name="test1"
]
]
What I want is array which looks similar to this. Mapping the id with name so it can be accessed and checked.
[
[1]=>'test'
[2]=>'test1'
]
Instead of using the ArrayHelper you can directly achieve the desired output by using indexBy() and column() within your query:
$data = User::find()
->select(['name', 'id'])
->where(['status' => 'active'])
->orderBy(['id' => SORT_DESC])
->indexBy('id')
->column();
indexBy() defines the array key, while column() will take the first column in the select condition as value.
Try this
Add the below namespace and use the arrayhelper of Yii2 to map
use yii\helpers\ArrayHelper
$userdata = ArrayHelper::map($data, 'id', 'name');
I have a problem with json,
I'm using PHP Curl to post file with form-data, and after post the Curl return some weird json
like this
{"code":200,"status":"Success","badges":{"id":"0d28f02d13fe4c7ca8681e2ed0224180","name":"test 5","description":"test 5","image":"http://somesite.id/images/d25273bdc1b54525a602dfca8ab826fdtest.jpg","category":"Upload","target":2}}
the problem is, the return result can't be json_decode, I know if this json weird, I can print but cannot be json_decode,
I not have acces to change API, I need the id from badges,
is there any trick? or a way to get the id, or some modified so the return result can be decode
i have tried
$a = 'that result';
$b = "'".$a."'";
$c = json_decode($b);
but it still json format, not become array
need some idea and help, thx
EDITED:
let's say
$result = {"code":200,"status":"Success","badges":{"id":"0d28f02d13fe4c7ca8681e2ed0224180","name":"test 5","description":"test 5","image":"http://somesite.id/images/d25273bdc1b54525a602dfca8ab826fdtest.jpg","category":"Upload","target":2}}
when I json_decode
$data = json_decode($result);
var_dump($result );
print_r($data);
it will return
{"code":200,"status":"Success","badges":{"id":"0d28f02d13fe4c7ca8681e2ed0224180","name":"test 5","description":"test 5","image":"http://somesite.id/images/d25273bdc1b54525a602dfca8ab826fdtest.jpg","category":"Upload","target":2}}bool(true) 1
try this
$js='{"code":200,"status":"Success","badges":{"id":"0d28f02d13fe4c7ca8681e2ed0224180","name":"test 5","description":"test 5","image":"http://somesite.id/images/d25273bdc1b54525a602dfca8ab826fdtest.jpg","category":"Upload","target":2}}';
var_dump(json_decode($js,true));
Your Output will be
array (size=3)
'code' => int 200
'status' => string 'Success' (length=7)
'badges' =>
array (size=6)
'id' => string '0d28f02d13fe4c7ca8681e2ed0224180' (length=32)
'name' => string 'test 5' (length=6)
'description' => string 'test 5' (length=6)
'image' => string 'http://somesite.id/images/d25273bdc1b54525a602dfca8ab826fdtest.jpg' (length=66)
'category' => string 'Upload' (length=6)
'target' => int 2
You don't want to put quotes around the string. Change
$a = 'that result';
$b = "'".$a."'";
$c = json_decode($b);
to simply
$a = 'that result';
$c = json_decode($a);
The JSON is valid. Putting the quotes around it made it invalid.
The original response is correct JSON syntax. Don't add the extra quotes in $b = "'".$a."'"; //INCORRECT
Instead try this, as an example:
/* $response is the result from API */
$response = '{"code":200,"status":"Success","badges":{"id":"0d28f02d13fe4c7ca8681e2ed0224180"}}';
$decoded = json_decode($response);
print_r($decoded); //See full decoded
$badge_id = $decoded->badges->id;
echo "The badge id is $badge_id \n";
Which would print:
stdClass Object
(
[code] => 200
[status] => Success
[badges] => stdClass Object
(
[id] => 0d28f02d13fe4c7ca8681e2ed0224180
)
)
The badge id is 0d28f02d13fe4c7ca8681e2ed0224180