Array to string conversion laravel 5.6 - php

$data = $request->all();
if (!empty($data))
{
foreach ($data as $key => $value)
{
if($key === "_token")
{
continue;
}
$val = [
'questionnaire_id' => $questionnaire_id,
'question_id' => $key,
'answer' => $value
];
$answer = Answer::create($val);
}
}
This is my array
{
"_token": "URP1tlRfoD0RFMYIgVIyBX1AYaobDsQU2wnvxC1r",
"questionnaires_id": "5",
"questions": {
"2": "a",
"10": "3",
"11": "b",
"44": "2018-08-01"
}
}
this is my model class
class Answer extends Model
{
protected $fillable = [
'questionnaire_id', 'question_id', 'answer'
];
}

Change your code like this
$qs = $request->questions;
$qr = $request->questionnaires_id;
foreach ($qs as $k => $q)
{
$val = [
'questionnaire_id' => $qr,
'question_id' => $k,
'answer' => $q
];
$answer = Answer::create($val);
}

If you want to convert only array to string, You should use php function like json_encode()

To store array in DB/Model you can do this:
protected $casts = [
'answer' => 'array'
];
And $answer can be:
$answer = array($your_data);

You should follow this flow.
$data = $request->all();
if (!empty($data))
{
$questionnaires_id = 0;
$questions = [];
foreach ($data as $key => $value)
{
if($key === "_token")
{
continue;
}
if($key === "questionnaires_id")
{
$questionnaires_id = $value;
}
if($key === "questions")
{
$questions = $value;
}
}
foreach ($questions as $key => $value) {
$val = [
'questionnaire_id' => $questionnaires_id,
'question_id' => $key,
'answer' => $value
];
$answer = Answer::create($val);
}
}

Related

PHP - make multidimensional array to array of strings from the arrays names

I have a multidimensional array like this:
array (
level1 => array ( level1.1,
level1.2)
level2 => array ( level2.1,
level2.2 => array( level2.2.1 => 'foo',
level2.2.2 => 'bar',
level2.2.3 => 'test')
)
)
As a result I want an array of strings like this
array ("level1/level1.1",
"level1/level1.2",
"level2/level2.1",
"level2/level2.2/level2.2.1",
"level2/level2.2/level2.2.2",
"level2/level2.2/level2.2.3")
Here is the code I tried
function displayArrayRecursively($array, string $path) : array {
if($path == "")
$result_array = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$this->displayArrayRecursively($value, $path . $key . '/');
} else {
$result_array[] = $path . $key; }
}
return $result_array;
}
Any idea how I can achieve this. I could use a reference array to populate, but I want to solve it with return values.
$array = [
'level1' => [
'level1.1',
'level1.2'
],
'level2' => [
'level2.1',
'level2.2' => [
'level2.2.1' => 'foo',
'level2.2.2' => 'bar',
'level2.2.3' => 'test'
]
]
];
function arrayParser(array $array, ?string $path=null) {
$res = [];
foreach($array as $key => $value) {
if(is_array($value)) {
$res[] = arrayParser($value, ($path ? $path.'/' : $path).$key);
}
else {
$res[] = $path.'/'.(!is_numeric($key) ? $key : $value);
}
}
return flatten($res);
}
function flatten(array $array) {
$return = array();
array_walk_recursive($array, function($a) use (&$return) { $return[] = $a; });
return $return;
}
$res = arrayParser($array); // result

Distribute array row data to make multiple new rows

I have below the data
[
{
"price_in_dollar": 1000,
"price_in_euro": 1000,
"price_in_pound": 1000,
"price_in_rupee": 1000,
"toy_id": 1,
"toy_name": "Truck"
},
{
"price_in_dollar": 1000,
"price_in_euro": 1000,
"price_in_pound": 1000,
"price_in_rupee": 1000,
"toy_id": 2,
"toy_name": "Bicycle"
}
]
I want to create a new array from above as below
[
{
"toy": "Truck",
"toy_id": 1,
"rate": 1000,
"slug": "price_in_dollar",
},
{
"toy": "Truck",
"toy_id": 1,
"rate": 1000,
"slug": "price_in_euro",
},
...
{
"toy": "Bicycle",
"toy_id": 2,
"rate": 1000,
"slug": "price_in_dollar",
},
{
"toy": "Bicycle",
"toy_id": 2,
"rate": 1000,
"slug": "price_in_euro",
},
...
]
I have tried the below code
foreach($data as $r) {
foreach($r as $key => $value) {
if ($key === 'toy_name') {
$cars['toy'] = $value ;
}
else if ($key === 'toy_id') {
$cars['toy_id'] = $value;
}
else {
$cars['slug'] = $key ;
$cars['rate'] = $value;
}
}
}
But it only has one set of data, how can I append all data? Or any improved code to solve this?
your code was actually replacing a key => value pair data, not pushing a data into $cars, you can fix it like this:
$cars = [];
foreach($data as $r) {
$singleCar = [
"toy_id" => $r['toy_id'],
"toy" => $r['toy_name'],
];
foreach($r as $key => $val){
if($key != 'toy_id' && $key != 'toy_name') {
$singleCar['rate'] = $val;
$singleCar['slug'] = $key;
$cars[] = $singleCar;
}
}
}
Something like the below is working fine:
$data= [
[
"price_in_dollar" => 1000,
"price_in_euro" => 1000,
"price_in_pound" => 1000,
"price_in_rupee" => 1000,
"toy_id" => 1,
"toy_name" => "Truck"
],
[
"price_in_dollar" => 1000,
"price_in_euro" => 1000,
"price_in_pound" => 1000,
"price_in_rupee" => 1000,
"toy_id" => 2,
"toy_name" => "Bicycle"
]
];
$cnt = 0;
foreach($data as $r) {
foreach($r as $key => $value) {
if ($key === 'toy_name') {
$cars[$cnt]['toy'] = $value ;
}
else if ($key === 'toy_id') {
$cars[$cnt]['toy_id'] = $value;
}
else {
$cars[$cnt]['slug'] = $key ;
$cars[$cnt]['rate'] = $value;
}
}
$cnt++;
}
// display result
print_r($cars);
try like
foreach($data as $r) {
foreach($r as $key => $value) {
if ($key === 'toy_name') {
$cars[]['toy'] = $value ;
}
else if ($key === 'toy_id') {
$cars[]['toy_id'] = $value;
}
else {
$cars[]['slug'] = $key ;
$cars[]['rate'] = $value;
}
}
}
I would loop for the different currencies and use some php array functions
$currencies = ['price_in_dollar', 'price_in_euro', 'price_in_pound', 'price_in_rupee'];
$data= [
...
];
$newData = [];
foreach($currencies as $currency) {
$newData = array_merge(
$newData,
array_map(function ($item) use ($currency) {
return [
"toy" => $item['toy_name'],
"toy_id" => $item['toy_id'],
"rate" => $item[$currency],
"slug" => $currency,
];
}, $data)
);
}
As you iterate each row, isolate the repeatable elements, then removed them from the row, then iterate the remaining elements and push the new desired associative rows into the result array.
The unset() call will not actually affect the original input array because the forearch is actually iterating a "copy" of the input array.
Code: (Demo)
$result = [];
foreach ($data as $row) {
['toy_id' => $id, 'toy_name' => $name] = $row;
unset($row['toy_id'], $row['toy_name']);
foreach ($row as $slug => $rate) {
$result[] = compact(['id', 'name', 'slug', 'rate']);
}
}
var_export($result);

How do I put multiple values in an array while foreaching through values in PHP

Alright so I'm trying to adjust an array and decode it to json, currently it decodes the array like this;
{"campaignId":"18210f12-502c-4d71-a098-4f595304a8d0","fields.CPLastName":"Voornaam 1","fields.CPFirstname":"Achternaam 1","fields.OROrganisation":"Bedrijf 1"}
{"campaignId":"18210f12-502c-4d71-a098-4f595304a8d0","fields.CPLastName":"Voornaam 2","fields.CPFirstname":"Achternaam 2","fields.OROrganisation":"Bedrijf 2"}
Code:
$request = array();
foreach($address_data as $address) {
foreach($address as $key => $value){
if($key == 'campaignId') {
$request[$key] = $value;
}
if (strpos($key, 'fields') !== false) {
$fields = explode('.', $key);
$request['fields'] = array(
array('fieldId' => $fields[1], 'value' => $value)
);
}
}
echo json_encode($request);
}
What I want to do is, where it says; fields. I want to explode on that and replace fields. with fieldId within a fields array. So something like this;
$request['fields'] = array(array('fieldId' => $key, 'value' => $value));
Now for some reason it will only do the last key, and I want it to loop through all the keys where it says 'fields.'
So the final request should look something like;
{
"campaignId":"18210f12-502c-4d71-a098-4f595304a8d0",
"fields": [
{
"fieldId":"CPLastName",
"value":"Voornaam 1"
},
{
"fieldId": "CPFirstname",
"value": "Achternaam 1"
},
{
"fieldId":"OROrganisation",
"value":"Bedrijf 1"
}
]
}
{
"campaignId":"18210f12-502c-4d71-a098-4f595304a8d0",
"fields": [
{
"fieldId":"CPLastName",
"value":"Voornaam 2"
},
{
"fieldId": "CPFirstname",
"value": "Achternaam 2"
},
{
"fieldId":"OROrganisation",
"value":"Bedrijf 2"
}
]
}
Use a temporary helper variable in cases like this, that you assemble the array data structure for a single item in.
Add that temp array to the result array at the end of the outer loop.
$request = [];
foreach($address_data as $address) {
$temp = [];
foreach($address as $key => $value){
if($key == 'campaignId') {
$temp[$key] = $value;
}
if (strpos($key, 'fields') !== false) { // === 0 would perhaps make more sense here
$fields = explode('.', $key);
$temp['fields'][] = [
'fieldId' => $fields[1],
'value' => $value
];
}
}
$request[] = $temp;
}
echo json_encode($request);

I have a question about php search associative array

I have this ff. assoc array
$array = [
'school' => [
'college' => [
'nursing' => ['n1a', 'n2a', 'n3a', 'n4a'],
'hrm' => ['h1a', 'h2a', 'h3a', 'h4a'],
'tourism' => ['t1a', 't2a', 't3a', 't4a'],
'it' => ['i1a', 'i2a', 'i3a', 'i4a'],
],
'senior' => [],
],
'business' => [
'office' => [
'dep1' => ['team1', 'team2'],
'dep2' => ['team1', 'team2'],
'dep3' => ['team1', 'team2'],
'dep4' => ['team1', 'team2'],
],
],
]
And I have this code, but this only search first level array.
function searchItemsByKey($array, $key) {
$results = array();
if (is_array($array))
{
if (isset($array[$key]) && key($array)==$key){
$results[] = $array[$key];
}
foreach ($array as $sub_array){
$results = array_merge($results, $this->searchItemsByKey($sub_array, $key));
}
}
return $results;
}
All I want is to search all keys in this array that will result all arrays associated with keys like:
searchItemsByKey($array, 'hrm');
That will return:
['h1a', 'h2a', 'h3a', 'h4a']
Thanks.
You can use array_walk_recursive,
$result = [];
$search = "hrm";
function searchItemsByKey($array, $key)
{
$retArr = [];
if (is_array($array)) {
if (!empty($array[$key])) {
return $array[$key];
}
foreach ($array as $val) {
$retArr = array_merge($retArr, searchItemsByKey($val, $key));
}
}
return $retArr;
}
$temp = searchItemsByKey($array, 'hrm');
Demo.

recursive array_key_search function PhP

Having this recursive function ($key can be numeric as array(0=>'value1',1=>'value2' or string as array('key1'=>'value1','key2'=>'value2')), being $key,
needle and $array haystack:
public function array_key_search($searched_key, $array = array()){
* #param $searched_key: Key to search.
* $array: Array with keys to check.
* Recursive method to check if a key exists in a multidemensional array.
* If key exists, it returns corresponding value.
*/
foreach($array as $key => $value){
$key = "$key";
if($key_value == false){
if($key == $searched_key){
return $value;
}else{
if(is_array($value)){
$key_value = self::array_key_search($searched_key, $value);
}
}
}
}
$key_value == is_null($key_value) ? false : $key_value;
return $key_value;
}
May I use if($key === $searched_key) instead of invoking my $key param as string for comparision?
This time I'm talking about performance because this function may be hard to process sometimes.
This does what you want
$arr = [
'key1' => [
'key1.1' => [
'key1.1.1' => 'key1.1.1',
'key1.1.2' => 'key1.1.2'
],
'key1.2' => [
'key1.2.1' => 'key1.2.1',
'key1.2.2' => 'key1.2.2'
],
],
'key2' => [
'key2.1' => [
'key2.1.1' => 'key2.1.1',
'key2.1.2' => 'key2.1.2'
]
]
];
function get_key_val($search_key, $arr){
foreach($arr as $key => $value){
if( is_array($value) ){
$result = get_key_val($search_key, $value);
if ($result){
return $result;
}
}else{
if ($search_key == $key){
return $value;
}
}
}
return null;
}
var_dump(get_key_val('key2.1.2', $arr));
RETURNS
string(8) "key2.1.2"

Categories