How to show parent and child items form array in php - php

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.

Related

Combing matched keys in an array

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'])
]);
}
}

Updating nested arrays with Laravel

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', ...];

Diff 2 arrays and remove missing elements

I try to update bigger array with some info from smaller array with same number of elements. Bigger array is generated every 24 hours but the smaller is generated every 4 hours but sometimes in smaller array there few elements less, so I want to delete these elements from bigger array but how I can do that?
Here is a first element of smaller array:
array(5) {
["category_id"]=>
string(1) "8"
["product_url"]=>
string(58) "http://example.net/?id=1752"
["price_bgn"]=>
float(142.8)
["price_eur"]=>
float(72.99)
["quantity"]=>
int(5)
}
Here is a first element of bigger array:
array(23) {
["product_id"]=>
string(4) "1752"
["product_sku"]=>
string(7) "SKU1752"
["category_id"]=>
string(1) "8"
["product_url"]=>
string(58) "http://example.net/?id=1752"
["additional_images"]=>
array(4) {
[0]=>
string(64) "http://example.net/vario.jpg"
[1]=>
string(73) "http://example.net/duraflex_logo1.jpg"
[2]=>
string(67) "http://example.net/YKK-logo.jpg"
[3]=>
string(67) "http://example.net/Air-mesh.jpg"
}
["variants"]=>
array(4) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "3"
[3]=>
string(1) "4"
}
["related_products"]=>
array(4) {
[0]=>
array(2) {
["product_id"]=>
string(2) "18"
["product_sku"]=>
string(5) "SKU18"
}
[1]=>
array(2) {
["product_id"]=>
string(3) "248"
["product_sku"]=>
string(6) "SKU248"
}
[2]=>
array(2) {
["product_id"]=>
string(4) "1755"
["product_sku"]=>
string(7) "SKU1755"
}
[3]=>
array(2) {
["product_id"]=>
string(4) "1833"
["product_sku"]=>
string(7) "SKU1833"
}
}
["manufacturer_id"]=>
string(1) "1"
["quantity"]=>
int(5)
["metadescription_bg"]=>
string(233) ""
["detaileddescription_bg"]=>
string(5342) ""
["metadescription_en"]=>
string(159) ""
["metakeywords_en"]=>
string(38) ""
["name_en"]=>
string(38) ""
["price_eur"]=>
float(72.99)
["shortdescription_en"]=>
string(138) ""
["detaileddescription_en"]=>
string(2485) ""
["images_url"]=>
string(51) "http://example.net/?idpics=3948"
["images"]=>
array(4) {
[0]=>
string(50) "http://example.net/pic6129.jpg"
[1]=>
string(50) "http://example.net/pic6164.jpg"
[2]=>
string(50) "http://example.net/pic6165.jpg"
[3]=>
string(50) "http://example.net/pic5745.jpg"
}
}
So if I match product urls I update prices. But how to remove element from bigger array if there is no matched url in smaller array? This is the code for update:
foreach($this->productLinks as $product) {
foreach($this->productLinksOld as $k => $productOld) {
if($product['product_url'] == $productOld['product_url']) {
$this->productLinksOld[$k]['price_bgn'] = $product['price_bgn'];
$this->productLinksOld[$k]['price_eur'] = $product['price_eur'];
$this->productLinksOld[$k]['quantity'] = $product['quantity'];
}
}
}
cheers,
George!
I make a little check for this but I don't know is this the best way to do this. This is the code:
$links = unserialize(file_get_contents($this->_tempProductLinksFile));
$links[] = array(
'category_id' => 8,
'product_url' => 'http://www.example.net/?id=1752123',
'price_bgn' => 1.2,
'price_eur' => 0.6,
'quantity' => 15,
);
$products = unserialize(file_get_contents($this->_tempFullProductInfoFile));
echo count($links).' | '.count($products).'<br />';
foreach($links as $l) {
$ll[] = $l['product_url'];
}
foreach($products as $p) {
$pp[] = $p['product_url'];
}
foreach($products as $k => $pm) {
if(!in_array($pm['product_url'], $ll)) {
echo 'This key doesn\'t exists in small array '.$k.'<br />';
}
}
foreach($links as $k => $lm) {
if(!in_array($lm['product_url'], $pp)) {
echo 'This key doesn\'t exists in big array '.$k.'<br />';
}
}
First 1 get cached content for small array as links and for big array as products. Then I make new sub array to links to check case if in small array is a product without whole info in big array. After all I make a count for 2 arrays and the result is:
1501 | 1503
Then I get only product URLs in other arrays to check for each product url in other array and the result is:
This key doesn't exists in small array 44
This key doesn't exists in small array 313
This key doesn't exists in small array 685
This key doesn't exists in big array 1500
Which means that last record in links (created manually) not exists in big array and 3 other urls from products array doesn't exists in small array. Also run time of this code is ~200ms on my old home machine which is good enough for me :)
If any one can give me a better solution I'll be very grateful :)
cheers, George!

Array Null Foreach

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

how do i convert this array?

i have the following array:
["addToCart"]=>
array(3) {
[1]=>
array(5) {
["aantal"]=>
int(1)
["film_id"]=>
string(1) "1"
["zaal_id"]=>
string(1) "1"
["dag"]=>
string(7) "maandag"
["seats"]=>
array(4) {
[0]=>
string(2) "67"
[1]=>
string(2) "68"
[2]=>
string(2) "69"
[3]=>
string(2) "70"
}
}
You can see that i have an array called "seats" inside the "addToCart" array.There are 4 items in the "seats" array.
what i would like to have is 4 separate arrays, they should all have the same content but each of them needs to have 1 value of "seats".
I'm not sure I got exactly what you're looking to do, but this would result in an array of arrays where each has only one seat:
$seatArrays = array();
foreach ($addToCart as $arr)
{
foreach ($arr["seats"] as $seat)
{
$seatArr = $arr; // Copy the original array
$seatArr["seats"] = $seat; // Replace the "seats" subarray with the current seat
$seatArrays[] = $seatArr;
}
}

Categories