This is my sample JSON data that I need to implode. During that time I'm getting an array to string conversion error.
JSON
{
"user_id" :"110" ,
"parent_id": "115",
"relation_name" : "justin",
"data" :[
{"relation_ship": "brohter"},
{"relation_ship": "sister"}
],
"sum_assured": "89745$-$48721",
"annual_primium":"00000$-$0006557",
"paid_status" : "0$-$1",
"ins_company_name" : "yes",
"renew_date": "2018-10-11$-$2018-10-23"
}
Here is my function for imploding, please help me fix this.
<?php
if (isset($data)) {
foreach ($data as $value) {
$data_insert['user_id'] = $user_id;
$data_insert['parent_id'] = $user_id;
$data_insert['relation_name'] = $data['relation_name'];
$data_insert['relation_ship'] = implode("$-$", $data['data']);
$data_insert['sum_assured'] = implode("$-$", $data['sum_assured']);
$data_insert['annual_primium'] = implode("$-$", $data['annual_primium']);
$data_insert['paid_status'] = implode("$-$", $data['paid_status']);
$data_insert['renew_date'] = implode("$-$", $data['renew_date']);
$data_insert['ins_company_name'] = implode("$-$", $data['ins_company_name']);
DB::table('health_tbl')->insert($data_insert);
}
return response()->json(['status' => 'Success', 'message' => 'Success']);
}
return response()->json(['status' => 'Failure', 'message' => 'Failed']);
You can't implode something that isn't an array. Implode is basically used to turn something like this:
array('something', 'something else')
Into something like this:
implode('<delim>', array('something', 'something else')) => "something<delim>something else"
Are you intending on exploding them to tear them into their own arrays?
In that case, use explode like this:
explode('$-$', $data['paid_status']);
That would return (using your data above):
array("0", "1")
Related
I am trying to pass a multi-dimensional array as a query parameter in the below URL:
{{serverURL}}/api/v1/classes?with[]=section.courseteacher&addl_slug_params[0][0]=test&addl_slug_params[0][1]=test1&addl_slug_params[0][2]=test0
what is wrong with the above URL?
My code to access these parameters in Laravel 6.0 is below:
$addl_slug_params = $request->query('addl_slug_params');
$i=0;
foreach ($addl_slug_params as $s) {
$j=0;
foreach($s as $asp) {
print_r('addl_slug_params : ('.$i.':'.$j.') : '.$asp); die();
$j=$j+1;
}
$i = $i+1;
}
Result:
addl_slug_params : (0:0) : test
Problem: test1 and test0 are not accessible..
What should I do?
The problem is the die(); after printr(), the loop will run once, aka only addl_slug_params : (0:0) : test
To help you visualize it better, I added an extra break after each loop:
foreach ($addl_slug_params as $s) {
$j=0;
foreach($s as $asp) {
echo('addl_slug_params : ('.$i.':'.$j.') : '.$asp);
echo nl2br(PHP_EOL);
$j=$j+1;
}
$i = $i+1;
}
Will result in the following:
addl_slug_params : (0:0) : test
addl_slug_params : (0:1) : test1
addl_slug_params : (0:2) : test0
here is a solution for multi-dimensional arrays. Developed in 2~ hours, definitely needs improvement but hopefully helps you out :)
Route::get('example', function (\Illuminate\Http\Request $request) {
$addl_slug_params = [
[
1 => [
'title' => 'Test 1',
'slug' => 'test1'
],
2 => [
'title' => 'Test 2',
'slug' => 'test2'
],
3 => [
'title' => 'Test 3',
'slug' => 'test3'
],
],
];
// Encode
$prepend = 'addl_slug_params';
$query = "?$prepend";
$tempSlugs = $addl_slug_params[0];
$lastIndex = count($tempSlugs);
foreach ($addl_slug_params as $pIndex => $params) {
foreach ($params as $sIndex => $slugData) {
$tempQuery = [];
foreach ($slugData as $sdIndex => $data) {
// Replace '-' or ' -' with ''
$encodedString = preg_replace('#[ -]+#', '-', $data);
// title = test1
$tempString = "$sdIndex=$encodedString";
$tempQuery[] = $tempString;
}
$dataQuery = implode(',', $tempQuery);
$appendStr = ($sIndex !== $lastIndex) ? "&$prepend" : '';
// Set the multidimensional structure here
$query .= "[$pIndex][$sIndex]=[$dataQuery]$appendStr";
}
}
// DECODE
// ?addl_slug_params[0][1]=[title=Test-1,slug=test1]&addl_slug_params[0][2]=[title=Test-2,slug=test2]&addl_slug_params[0][3]=[title=Test-3,slug=test3]
$slugParams = $request->query('addl_slug_params');
$slugParamData = [];
foreach ($slugParams as $slugItems) {
foreach ($slugItems as $slugItem) {
// Replace [title=test,slug=test1] into 'title=test,slug=test1' and explode
// into into an array, and split title=test into [title => test]
$splitArray = explode(',', (str_replace(array('[', ']'), '', $slugItem)));
$slugItemData = [];
foreach ($splitArray as $value) {
$data = explode('=', $value);
$slugItemData[$data[0]] = $data[1];
}
$slugParamData[] = $slugItemData;
}
}
dd($slugParamData);
});
I have solved the problem using associative arrays as it gives more flexibility and Garrett's solution definitely helped
new url: {{serverURL}}/api/v1/classes?with[]=section.courseteacher&addl[users][params]=name
laravel code:
`
foreach ($addl_data_array as $addl_slug => $addl_slug_data) {
foreach ($addl_slug_data as $key => $value) {
$params = null;
$where_raw = null;
$where_has = null;
$with_relationships = null;
$with_timestamps = null;
}
}
`
I have the following problem: I have a table for customers, with a prename and a name. Now I have variable keywords (in this example hardcoded 2) in an array and I want to check whether one of the keywords match with either the name OR the prename. So I figured to use the OR condition in the following codesnippet. Unfortunately it doesnt provide the wanted output:
$searchValueArr = ["keyword1","keyword2"];
$customers = $customersTable->find()
->where(function (QueryExpression $exp) {
$orConditions = $exp->or_(function ($or) {
foreach($searchValueArr as $searchValue) {
$or = $or
->eq('prename LIKE', "%".$searchValue."%")
->eq('name LIKE', "%".$searchValue."%");
}
return $or;
});
return $orConditions;
})
->all();
You need to list $searchValueArr in the use part of each anonymous function, otherwise it's not in context, ex:
$searchValueArr = ["keyword1","keyword2"];
$customers = $customersTable->find()
->where(function (QueryExpression $exp) use ($searchValueArr){
$orConditions = $exp->or_(function ($or) use ($searchValueArr){
foreach($searchValueArr as $searchValue) {
$or = $or
->eq('prename LIKE', "%".$searchValue."%")
->eq('name LIKE', "%".$searchValue."%");
}
return $or;
});
return $orConditions;
})
->all();
Also this is personal preference really, but you technically can still use array formatting for a query like this (a nested set of OR's), for example:
$searchValueArr = ["keyword1","keyword2"];
$searchTerms = [];
foreach($searchValueArr as $searchValue) {
$searchTerms[] = [
'OR' => [
'prename LIKE' => "%".$searchValue."%",
'name LIKE' => "%".$searchValue."%"
]
];
}
$customers = $customersTable->find()
->where([
'OR' => $searchTerms
])
->all();
Good afternoon !
I am creating a private chat , and I get the first objective , get the message and users with the following code.
public function getEnviarMensajes($id,$identificador){
$user = User::find($identificador);
$idReceptor = $user->id;
$idEmisor = Auth::user()->id;
$mesageuser = MessageUser::with('user')->with('message')->get();
$name = [];
$content = [];
foreach($mesageuser as $users){
foreach($users->message as $mensajes){
if($users->user->id==$idEmisor){
$name[] = $users->user->name;
echo "<p>";
$content[] = $mensajes->contenido;
echo "<p>";
echo $mensajes->created_at;
echo "<p>";
}
if($users->user->id==$idReceptor){
$name[] = $users->user->name;
echo "<p>";
$content[] = $mensajes->contenido;
echo "<p>";
echo $mensajes->created_at;
echo "<p>";
}
}
}
However , I have a problem , this results i need to "join" , in many ocasions I used an array , but in this case ? How I can save differents rows in Laravel ? , also I need to sort this content for datetime row.
Could anyone helps to me ?
I think you can cut your code at this way:
$mesageuser = MessageUser::with('user')->with('message')->get();
$messages = [];
foreach($mesageuser as $users){
foreach($users->message as $mensajes){
$messages[] = [
'nombre' => $users->user->name,
'contenido' => $mensajes->contenido,
'creado' => $mensajes->created_at,
'emisor' => ($users->user->id==$idEmisor) // true or false
];
}
}
return view('chat', ['messages' => $messages]);
The two if statements are useless because inside of them the code is the same. And I had used an multidimensional array in order to store all the messages with the following structure:
[
[
'nombre' => 'Marta',
'contenido' => 'Hola',
'creado' => '24/03/2015',
'emisor' => false
],
[
'nombre' => 'Salomé',
'contenido' => 'adiós',
'creado' => '24/03/2015',
'emisor' => true
]
]
If you want, for example, order by date, then edit your query:
$mesageuser = MessageUser::with('user')->with(['message' => function($query){
$query->orderBy('created_at', 'desc');
}])->get();
I am trying to store the FBIDs of a Facebook user's friends in the column of a mysql database. I've tried looking up other answer on this issue, and I have tried to implement it (in Laravel 4). Here is what I have done:
In the Facebook.php file, one of the providers:
'friends' => 'https://graph.facebook.com/me/friends?access_token='.$token->access_token
In my Oauth2 Controller:
$friends_list = $user['friends'];
$friends_list_array = json_decode($friends_list,true);
$arr= $friends_list_array['data'];
$friend_ids_arr = array();
foreach($arr as $friend) {
$friend_ids_arr[] = $friend['id'];
}
$friend_ids = implode("," , $friend_ids_arr);
And then I want to store the $friend_ids object in a "text" column in my database. However, when running this, I keep getting the error: Invalid argument supplied for foreach()
But it is very clearly being supplied an array as it should. Is there something I'm not seeing? Thank you for your help.
Actually the returned result is a json, the returned object should look something like this
{
"id": "xxxxxxx",
"name": "Sheikh Heera",
"friends": {
"data": [
{ "name": "RaseL KhaN", "id": "xxx" },
{ "name": "Yizel Herrera", "id": "xxx" }
],
"paging": {
"next": "https://graph.facebook.com/xxx/friends?limit=..."
}
}
}
After you json_decode
$user = json_decode($user, true);
It should look something like
Array
(
[id] => xxxxxxx
[name] => Sheikh Heera
[friends] => Array
(
[data] => Array
(
[0] => Array
(
[name] => RaseL KhaN
[id] => xxx
)
[1] => Array
(
[name] => Yizel Herrera
[id] => xxx
)
)
[paging] => Array
(
[next] => https://graph.facebook.com/xxx/friends?limit=...
)
)
)
So, now you can
$friends_list = $user['friends'];
$data = $friends_list['data'];
Make sure your $data array is not empty and then loop
if(count($data)) {
$friend_ids_arr = array();
foreach($data as $friend) {
$friend_ids_arr[] = $friend['id'];
}
}
So, the foreach will run only when $data has items in it.
Update: It may help you
$url = "https://graph.facebook.com/me?fields=id,name,friends&access_token=YOUR_ACCESS_TOKEN";
$contents = json_decode(file_get_contents($url), true);
$friends = $contents['friends'];
$friend_ids_arr[]
foreach($friends['data'] as $friend)
{
$friend_ids_arr[] = $friend['id'];
}
Do we have any array function in PHP to get this:
// get all the user ids as comma seprated.
$users = array();
foreach($view as $result)
{
$users[] = $result->uid;
}
$uid = implode(',', $users);
Example:
$array[0] = array("size" => "XL", "color" => "gold");
$array[1] = array("size" => "XLL", "color" => "siver");
$array[2] = array("size" => "M", "color" => "purple");
I need
$color = "gold,silver,purple";
Thanks in Advance for your help.
You can use explode(',', $view) in order to get the values array.
From your updated question:
You could try something like this:
'firstname_value','lastname'=>'lastname_value');
sprintf('INSERT INTO %s (%s) VALUES ("%s")', 'table_name', implode(', ', array_map('mysql_escape_string', array_keys($values))), implode('", "',array_map('mysql_escape_string', $values)));
//that gives you: INSERT INTO table_name (firstname, lastname) VALUES ("firstname_value", "lastname_value")
?>