First sorry, i am only developing in php for a month and i do not know how to update this with laravel
I would like to update multiple photos.
Photos have a title description, etc.
My problem is i have no clue how to do it.
I tried the following
public function update(Request $request, Photo $photo)
{
// loop through array of id's
foreach ($request->photo_id as $id)
{
// find
$photos = $photo->find($id);
// loop throug input fields
foreach ($request->except('_token', 'tags', 'photo_id') as $key => $value)
{
$photos->$key = $value;
$photos->save();
}
}
die();
}
I get the following error
preg_replace(): Parameter mismatch, pattern is a string while replacement is an array
So i figured out the problem is with the value
And the results are like this
Key variable
string(5) "title"
string(10) "country_id"
string(7) "city_id"
string(11) "category_id"
string(9) "cruise_id"
string(12) "itinerary_id"
string(4) "desc"
string(6) "people"
string(5) "title"
string(10) "country_id"
string(7) "city_id"
string(11) "category_id"
string(9) "cruise_id"
string(12) "itinerary_id"
string(4) "desc"
string(6) "people"
Value variable results
array(2) {
[0]=>
string(9) "title one"
[1]=>
string(9) "title two"
}
array(2) {
[0]=>
string(1) "1"
[1]=>
string(1) "1"
}
array(2) {
[0]=>
string(1) "1"
[1]=>
string(1) "1"
}
array(2) {
[0]=>
string(0) ""
[1]=>
string(0) ""
}
array(2) {
[0]=>
string(1) "1"
[1]=>
string(0) ""
}
array(2) {
[0]=>
string(1) "1"
[1]=>
string(0) ""
}
I tried several other attempts but nothing works
Could please someone help me out with this?
Without knowing more about what is passing you the request object, I can't really go into specifics but you probably want to get your request object to look something like this:
'photos' => [
{
'id' => 1,
'title' => 'title one',
// more properties ....
},
{
'id' => 2,
'title' => 'title two',
// more properties ....
},
]
Then try something like this:
public function update(Request $request)
{
// Loop through the request photo id's
$request->photos->each(function($photo) use ($request) {
// Return the photo object you want to update
$photo = Photo::find($photo->id);
// Get the things you want from the request and update the object
$photo->title= $request[$photo_id]->title;
// Save the object
$photo->save();
})
}
You also may want to try out the dd(); function instead of die();. It makes debugging a lot easier.
I think, Photo Model missed the fillable array.
protected $fillable = ['var1', 'var2', ...];
Related
I am new at php. Maybe a simple question.. I want to make parent->child view. I have an array like this:
With key id and key parent.
How to draw in cycle correct structure? Maybe at first I need to create function for creating the tree ?
-Apple
-Services
Duster
array(3) {
[0]=>
array(6) {
["id"]=>
string(3) "127"
["title"]=>
string(5) "Apple"
["deleted"]=>
string(1) "0"
["parent"]=>
NULL
["usp_id"]=>
string(3) "445"
["user_id"]=>
NULL
}
[1]=>
array(6) {
["id"]=>
string(3) "159"
["title"]=>
string(14) "Renault Duster"
["deleted"]=>
string(1) "0"
["parent"]=>
NULL
["usp_id"]=>
string(3) "495"
["user_id"]=>
NULL
}
[2]=>
array(6) {
["id"]=>
string(1) "7"
["title"]=>
string(8) "Services"
["deleted"]=>
string(1) "0"
["parent"]=>
string(3) "127"
["usp_id"]=>
string(2) "79"
["user_id"]=>
string(3) "275"
}
}
Cycle through the source array $arr to detect records that have a parent (not null). When a child record is found, push it into the parent.
foreach ($arr as $key0 => $record) {
if (null !== $record['parent']) {
foreach ($arr as $key1 => $parent) {
if ($parent['id'] === $record['parent']) {
$arr[$key1]['children'][] = $record; // push child into parent
unset($arr[$key0]); // delete child
}
}
}
}
demo
A simple and common idea is to prepare your data for easy printing. In your case, you need to group your data so that each item includes parent and children data.
Create a temporary array ($temp). Each item would be something like this:
['id' =>, 'name' => '', children => ['name' => '']]
And iterate through your original array ($curr) two times.
First pass:
parent is not null:
$temp[$curr['parent']]['children'][] = ['name' => $curr['name']]
parent is null:
$temp[$curr['id']] = ['name' => $curr['name'], 'children' => []]
In the second pass simply print it since you already have everything grouped.
Edited
I get the combined item_ids now, but not the single item_ids.
I have an array with three keys.
$searchArray = {
[0]=> array(3) {
["keyword"]=> string(7) "history"
["url"]=> string(7) "history"
["item_id"]=> string(2) "16"
}
[1]=> array(3) {
["keyword"]=> string(4) "past"
["url"]=> string(4) "past"
["item_id"]=> string(2) "16"
}
[89]=> array(3) {
["keyword"]=> string(10) "biomedical"
["url"]=> string(10) "biomedical"
["item_id"]=> string(2) "34"
}
[93]=> array(3) {
["keyword"]=> string(10) "biomedical"
["url"]=> string(10) "biomedical"
["item_id"]=> string(2) "35"
}
I want to combine the options that have the same keyword/url.
Just need to check if keyword matches.
The final format needs to be something that jquery autocomplete can accept, where I can assign the text to keyword and the value to url, id to the item_id.
There were only two keys in the array before and I would combine matches this way.
foreach ($searchArray as $row)
{
$combineMatches[ $row['keyword'] ][] = $row['item_id'];
}
result after using json_encode():
"anthropologist":["27","37"],
"biomedical":["34","35"],
"m.s.":["18","19","23"]
What I currently have:
$combineMatches = array();
foreach ($searchArray as $row)
{
$match =
array_search($row['keyword'],array_column($combineMatches,'keyword'));
if($match){
$combineMatches[$match]['item_id']+= $row['item_id'];
}else{
array_push($combineMatches, [
'keyword' => $row['keyword'],
'url' => $row['url'],
'item_id' => array_push($row['item_id'])
]);
}
}
Result:
[7]=> array(3)
{
["keyword"]=> string(8) "theology"
["url"]=> string(8) "theology"
["item_id"]=> NULL
}
[13]=> array(3)
{
["keyword"]=> string(7) "writing"
["url"]=> string(7) "writing"
["item_id"]=> NULL
}
How do I add to the array column of just item_id ? Which I see is a string, but I need as an array.
This gets JSON encoded in the end of the PHP and read by jquery autocomplete.
Thank you for pointing out the string/array issue.
I changed how to add to the third key if there is a match, and if there isn't a match the solution was changing the array_push to just array.
$combineMatches = array();
foreach ($searchArray as $row)
{
$match=array_search($row['keyword'],array_column($combineMatches,'keyword'));
if($match){
$combineMatches[$match]['item_id'][] = $row['item_id'];
}else{
array_push($combineMatches, [
'keyword' => $row['keyword'],
'url' => $row['url'],
'item_id' => array($row['item_id'])
]);
}
}
I'm very new to PHP and I need your help!
I need to write backend for my app that receives json post and write data to json file. And I'm stuck with looping through array.
$postData = file_get_contents("php://input");
$request = json_decode($postData);
var_damp($request)
shows array:
array(2) {
[0]=>
object(stdClass)#1 (8) {
["name"]=>
string(11) "Alex Jordan"
["email"]=>
string(14) "alex#gmail.com"
["phone"]=>
int(123456789)
["street"]=>
string(12) "street, str."
["city"]=>
string(7) "Chicago"
["state"]=>
string(7) "Chicago"
["zip"]=>
string(5) "07202"
["$$hashKey"]=>
string(8) "object:3"
}
[1]=>
object(stdClass)#2 (8) {
["name"]=>
string(15) "Michael Jonhson"
["email"]=>
string(17) "michael#gmail.com"
["phone"]=>
float(11987654321)
["street"]=>
string(12) "street, str."
["city"]=>
string(11) "Los Angeles"
["state"]=>
string(10) "California"
["zip"]=>
string(5) "27222"
["$$hashKey"]=>
string(8) "object:4"
}
}
I'm trying to loop through the objects and getting error
Object of class stdClass could not be converted to string
Here is how I'm trying to do it:
foreach($request as $i => $i_value) {
echo $i_value;
}
$i_value is the object. Because it's an object you cannot just echo it (unlike in JavaScript where you can cast any object to string).
You can echo specific properties of the object:
foreach($request as $i => $i_value) {
echo $i_value->name;
}
Of course you could also use var_dump again to dump each object. print_r should work too.
Objects can only be casted to string like you do if they implement the __toString() magic method, but the objects created by json_decode are just simple StdClass objects that do not implement this. It's probably not your intention to do this at all, but if you're curious, you may have a look at json_decode to custom class to see how you may use a custom class instead of StdClass.
I had the same problem recently. I used a for loop to loop through the array which gave me an error of undefined offset. Using isset() solved the error of undefined offset. I know its too late to answer this question but here it is for someone who might be looking for it in future
$postData = file_get_contents("php://input");
$request = json_decode($postData);
// or you can do $postData = json_decode(file_get_contents("php://input"));
$arrayOfUsers = $request->data; // I used a key of data while sending the array via fetch API
for($x = 0; $x < count($arrayOfUsers); $x++)
{
if(isset($arrayOfUsers[$x]))
{
$name = $arrayOfUsers[$x]->name;
$email = $arrayOfUsers[$x]->email;
$phone = $arrayOfUsers[$x]->phone;
$street = $arrayOfUSers[$x]->street;
// .... and so on
// then you can do whatever you want with the data
} else {
echo "No Data Found";
}
}
You can also use array_map(?callable $callback, array $array, array ...$arrays): array
to get required properties of each object;
or even alter its data.
This code covers both cases (sandbox_url):
<?php
$arr_of_objects[] = (object)['field_name' => 'test2', 'id' => 2];
$arr_of_objects[] = (object)['field_name' => 'test', 'id' => 1];
$array_of_names = array_map(function ($el) {
return $el->field_name;
}, $arr_of_objects);
echo 'get field_name from array of objects' . "\n";
var_dump($array_of_names);
$replace_data_with = [
1 => ['field_name' => 'replaced_name_1', 'id' => 777],
2 => ['field_name' => 'replaced_name_2', 'id' => 999]
];
$changed_values = array_map(function ($el) use ($replace_data_with) {
$el->field_name = $replace_data_with[$el->id]['field_name'];
$el->id = $replace_data_with[$el->id]['id'];
return $el;
}, $arr_of_objects);
echo 'alter data of each object' . "\n";
var_dump($changed_values);
Base array of Objects:
array(2) {
[0]=>
object(stdClass)#1 (2) {
["field_name"]=>
string(5) "test2"
["id"]=>
int(2)
}
[1]=>
object(stdClass)#2 (2) {
["field_name"]=>
string(4) "test"
["id"]=>
int(1)
}
}
Output:
get field_name from array of objects
array(2) {
[0]=>
string(5) "test2"
[1]=>
string(4) "test"
}
alter data of each object
array(2) {
[0]=>
object(stdClass)#1 (2) {
["field_name"]=>
string(15) "replaced_name_2"
["id"]=>
int(999)
}
[1]=>
object(stdClass)#2 (2) {
["field_name"]=>
string(15) "replaced_name_1"
["id"]=>
int(777)
}
}
following problem: I want to build a mysql based language system.
To decrease loading time and increase performance I thought it would be the best, to first fetch all Language phrases into an array (which happens with mysqli fetch array). Then, if a language term is required, calling a function with the array as global variable.
My function for the array:
$sql = $db->query('SELECT * FROM lang_phrases WHERE phraseLanguageId = 1');
$phrases = array();
while($row = $sql->fetch_array()) {
$phrases[] = $row;
}
Now I've got this array:
array(2) {
[0]=> array(8) {
[0]=> string(1) "1"
["phraseId"]=> string(1) "1"
[1]=> string(1) "1"
["phraseLanguageId"]=> string(1) "1"
[2]=> string(4) "HOME"
["phraseKey"]=> string(4) "HOME"
[3]=> string(10) "Homepage"
["phraseContent"]=> string(10) "Homepage"
}
[1]=> array(8) {
[0]=> string(1) "2"
["phraseId"]=> string(1) "2"
[1]=> string(1) "1"
["phraseLanguageId"]=> string(1) "1"
[2]=> string(4) "BACK"
["phraseKey"]=> string(4) "BACK"
[3]=> string(6) "Back"
["phraseContent"]=> string(6) "Back"
}
}
And thats my function:
function l($key) {
global $phrases;
return PLACEHOLDER;
}
I wonder, how can I now search the array for "phraseKey" $key from the function and get the value?
Do you have any hints? Or shall I simply select each phrase with each one query (performance problems with 100 quers per load?!)?
Cheers and Thanks!
That's a bad structure. Why not key your array with the phrase ID and the language? e.g.
$translations = array(
'HOME' => array(
'english' => 'Home',
'french' => 'Maison',
'german' => 'Haus"
etc...
This eliminates the need for ANY searching. You just look up directly by language/phrase ID.
May I suggest to retrive the phrases with
while($row = $sql->fetch_array()) {
$phrases[$row['phraseKey']] = $row;
}
Then in your function l($key) you can search them with
$t = isset($phrases[$key]) ? $phrases[$key] : null
Morning everyone,
My problem seems to be in my foreach loop but I cant see the issue.
When I print my array I get this from my select statment.
array(41) {
[0]=> array(4) {
["id"]=>
string(1) "1"
["name"]=>
string(14) "Indoor Cycling"
["time"]=>
string(12) "6.15am – 7am"
["day"]=>
string(1) "1"
}
[1]=> array(4) {
["id"]=>
string(2) "73"
["name"]=>
string(11) "Fast Blast "
["time"]=>
string(6) "7.10am"
["day"]=>
string(1) "5"
}
}
So I try the standard for each loop.
foreach ($rows as $timetableitems) {
$timetablearray[] = array(
'name' => $timetableitems->name,
'time' => $timetableitems->time,
);
}
But when I try and var dump my $timetablearray I get the following.
array(41) {
[0]=>
array(2) {
["name"]=>
NULL
["time"]=>
NULL
}
[1]=>
array(2) {
["name"]=>
NULL
["time"]=>
NULL
}
Any help would be most appreciated, thanks.
foreach ($rows as $timetableitems) {
$timetablearray[] = array(
'name' => $timetableitems['name'],
'time' => $timetableitems['time'],
);
}
You can not access array variables by $timetableitems->name. You have to use $timetableitems['name']
Instead of calling:
$timetableitems->name
use:
$timetableitems['name']
Because $timetableitems is an array, not an object. So you access its properties with key.
Try $timetableitems['name'] Instead of $timetableitems->name
$timetableitems is an array so you can use $timetableitems[] this format