In a SQL loop how to I amend to a sub-array? - php

I am trying to add data in from SQL loop into a specific section of an array, however it does't seem to keep the array format when I do a json encode.
I create the array:
$array['type'] = 'update';
$array['tags']['data'] = array(array('name' => "Tag", 'tags' => array()));
Then in my sql loop in the while:
$array['tags']['data']['tags'][] = array('a' => "$row[a]", 'b' => "$row[b]");
after this loop, json encode:
json_encode($array);
In the output, the "tags" has the rows added under data, and the one I setup for the array is now under tags:data:0:tags , and it has not populated this.
Also data has gone from [ ] to { }, and I need it to be [{ }]. If I take out the loop, the data section is with [ { } ] as expected.
Hope that makes sense! if not can expand more.
Many thanks

You have an extra array between data and tags
$array['tags']['data'] = array(array('name' => "Tag", 'tags' => array()));
print_r($array);
Output
Array
(
[tags] => Array
(
[data] => Array
(
[0] => Array
(
[name] => Tag
[tags] => Array
(
)
)
)
)
)
Then you try to access (for assignment)
$array['tags']['data']['tags'][] = array('a' => "$row[a]", 'b' => "$row[b]");
Which based on your $array should actually be
$array['tags']['data'][0]['tags'][]
Or something like that...
Without more to actually go on that's the best I can do, this really doesn't rate a answer, but there was no way to illustrate an array with that much nesting within a comment.
What you'll wind up with is something like this:
Array
(
[tags] => Array
(
[data] => Array
(
[0] => Array
(
[name] => Tag
[tags] => Array
(
)
),
[tags] => Array
(
[0] => Array
(
a => "$row[a]",
b => "$row[b]"
)
[1] => Array(...)
)
)
)
)
Which because of the mixed keys ['data' => [0 => ['name'=>'Tag',...], 'tags' => [...]] Will give you a JSON object at that location {data : {0:{name:"Tag",...},tags:[]}}
P.S this really annoys me "$row[a]" - I don't know why but it does ... lol

Related

Unwrap array inside another array PHP

I am getting a string separated from commas and I am trying to split them into an array, which works. The only problem is that there is an outer array wrapping the array I want to use. So I don't want to use the $excludes[0] when passing the array to a function. Does anyone know a function I can use to unwrap the array inside $excludes[0]
$excludes = [];
Array ( [0] => Array (
[0] => company_logo,
[1] => social_links,
[2] => rss_link,
[3] => telephone ) )
My expected results would be the below.
Array (
[0] => company_logo,
[1] => social_links,
[2] => rss_link,
[3] => telephone
)
You can simple do :
1st Option:
print_r(array_shift($excludes));
2nd Option:
$new_array = $excludes[0];
print_r($new_array);
Hope this will work
check this
$excludes = Array ( 0 => Array (
0 => 'company_logo',
1 => 'social_links',
2 => 'rss_link',
3 => 'telephone' ) ) ;
$excludes=$excludes[0];
print_r($excludes);die();

split one array have two key split into two array in php

Question :
I have one array have two key or more split into two or more create array based on array in php.
my Array :
array
(
[RAJAHMUNDRY] => Array
(
[unspcp_code] => 46182005
[title] => 3M™ Half Face Reusable Respirator HF-52 with Holder 1700 And Filter 1744
[total] => 2
[head_quarter] => RAJAHMUNDRY
[0] => 2
)
[HYDERABAD] => Array
(
[unspcp_code] => 46182005
[title] => 3M™ 6200 HALF FACE MASK WITH 7093 FILTER
[total] => 2
[head_quarter] => HYDERABAD
[0] => 2
)
)
I want output like this :
output:
array
(
[RAJAHMUNDRY] => Array
(
[unspcp_code] => 46182005
[title] => 3M™ Half Face Reusable Respirator HF-52 with Holder 1700 And Filter 1744
[total] => 2
[head_quarter] => RAJAHMUNDRY
[0] => 2
)
)
)
array(
[HYDERABAD] => Array
(
[unspcp_code] => 46182005
[title] => 3M™ 6200 HALF FACE MASK WITH 7093 FILTER
[total] => 2
[head_quarter] => HYDERABAD
[0] => 2
)
)
I am not sure how you want to store those arrays, but let me help you.
I assume you have a datastructure like this, so one array with multiple values.
array (
key1 => ...values...,
key2 => ...values...,
...
key_n => ...values...
)
And you want something like this, si multiple arrays with single keys well you need to store that array somehow.
array (
key1 => ...values...
)
array (
key2 => ...values...
)
...
array (
key_n => ...values...
)
If you do not know the exact number of arrays, you can't $array1, $array2, ... $array_n and it also not efficent, so you shoudl have an array of arrays. So something like this:
array(
array (
key1 => ...values...
)
array (
key2 => ...values...
)
...
array (
key_n => ...values...
)
)
So you should iterate trough the keys of the input array and then
So the code
<?php
//example input array
$arr = array (
"key1" => "val1",
"key2" => "val2"
);
$keys = array_keys($arr); //get the keys of the input array, see phpdoc
$output = [];
foreach($keys as $key) {
$output[] = array ($arr[$key]);
}
?>
This will output an array of arrays, with single key of the inner array.
If this is not you answer, reply.
Research:
https://www.php.net/manual/en/function.array-keys.php
https://www.php.net/manual/en/control-structures.foreach.php
php.net - arrays manual Example #6 Accessing array elements
Maybe this document will help you
This may also help you
<?php
$stdArray = array(
"foo" => "bar",
42 => 24,
"dimensional" => array(
"fname" => "jon",
"lname" => "doe",
),
"multi" => array(
"RAJAHMUNDRY" => array(
"unspcp_code" => 46182005,
"head_quarter" => "RAJAHMUNDRY",
0 => 2
),
"HYDERABAD" => array(
"unspcp_code" => 46182005,
"head_quarter" => "HYDERABAD",
0 => 2
),
)
);
print_r($stdArray);
print_r($stdArray["multi"]);
print_r($stdArray["multi"]["RAJAHMUNDRY"]);

Adding variable to upcomming array

I have a multi dimensional array with some values coming from a foreach, i need to insert this values into the array, but at this moment my result is this, not sure why:
Array
(
[0] => Array
(
[title] => MySecure
)
[1] => Array
(
[productTitle] => My New Product
)
[2] => Array
(
[title] => My Second Company
)
[3] => Array
(
[productTitle] => Another Product
)
[4] => Array
(
[productTitle] => Away Product
)
)
This is wrong, what i need is:
Array
(
[0] => Array
(
[title] => MySecure
[productTitle] => My New Product
)
[2] => Array
(
[title] => My Second Company
[productTitle] => Another Product
[productTitle] => Away Product
)
)
So this is what i have done:
$companies[] = [
'title' => $getCompanie->getTitle()
];
Then inside products :
$companies[] = [
'productTitle' => $getProduct->getTitle(),
];
so i assume im using the wrong array call, not sure about array_push?
You need to add both keys in the same inner array, rather than pushing them separately.
Use nested loops to get all the products associated with a company in the same loop.
$companies = [];
foreach ($all_companies as $companie) {
$products = [];
foreach ($companie->getProducts() as $getProduct) {
$products[] = $getProduct->getTitle());
}
$companies[] = [
'title' => $companie->getTitle(),
'productTitle' => $products
]
}
I've had to make up names for some of the things I assumed are in your code. You should be able to extrapolate from this to your actual design.
$newArray= [
'title' => array_map($yourArray,fn($ar)=>$ar['title']),
'productTitle' => array_map($yourArray,fn($ar)=>$ar['productTitle'])
];

Joining arrays to go in to a multidimensional array

I need to dynamically produce child elements of an array, these are arrays them selves. So the end result should be (this is a simplified version of the code below to make it easier to understand):
Array
(
[id] => 5000038642
[name] => TrackVia Legacy Section of Array
[description] =>
[table_id] => 5000005024
[records] => Array
(
[0] => Array
(
[id] => 1
[table_id] => 1
[fields] => Array
(
[Name] => First Item
)
)
[1] => Array
(
[id] => 1
[table_id] => 1
[fields] => Array
(
[Name] => Second Item
)
)
)
)
The nested arrays within Results are produced dynamically from a MySQL table, so >
$allItems = array();
$item = array();
// Get each result and build the arrya
while($row = $resultAvailableBoxes->fetch_assoc()) {
$item = array (
"id"=> $row['id'],
"table_id"=> $row['id'],
"fields"=> array (
"Name"=> $row['box_title'],
)
);
// Append the arrays on to each other
$allItems[] = array_merge($allItems, $item);
}
// Place the arrays within the "parent" array
$completeArray = array(
"id"=> 1000,
"name"=> "Sample",
"description"=> "",
"table_id"=> 1000,
"records"=>
$allItems
);
As you can see I am then also trying to append each new array on to the last, before placing those arrays in to the "parent" array. This is where the problems happen.
Using the method
$allItems[] = array_merge($allItems, $item);
I get every array appended on to the last, but then again and again. Like this:
Array
(
[id] => 5000038642
[name] => TrackVia Legacy Section of Array
[description] =>
[table_id] => 5000005024
[records] => Array
(
[0] => Array
(
[id] => 1
[table_id] => 1
[fields] => Array
(
[Name] => Texan BBQ 1
)
)
[1] => Array
(
[0] => Array
(
[id] => 1
[table_id] => 1
[fields] => Array
(
[Name] => Texan BBQ 1
)
)
[id] => 9
[table_id] => 9
[fields] => Array
(
[Name] => Goan Sorpotel with Pea & Mint Pilau and Tomato Chutney
)
)
)
)
When I have 20 items, you can see this would become massive list and just doesn't work. Using the method
$allItems = array_merge($allItems, $item);
Returns only the last array being appended (i.e. it always overwrites whats already in the "allItems" array.
I have also used a simple method that I didn't expect to work, and sure enough it didnt:
$allItems .= $item;
I've come to the conclusion after reading these stackover flow questions which seem like the same thing but aren't or give weird results that I must be approaching this all wrong. Is this the wrong method full stop, or is it that I have missed something out to stop the child elements being continually added?
Appending Arrays (Stack Overflow)
Can't concatenate 2 arrays in PHP
I've lost count of the other questions I've look at on this, including the PHP manual but I can't find anything more relevant the arrays_merge
why don't you just do this?
$items = array();
while($row = $resultAvailableBoxes->fetch_assoc()) {
$items[] = array (
"id"=> $row['id'],
"table_id"=> $row['id'],
"fields"=> array (
"Name"=> $row['box_title'],
)
);
}
// Place the arrays within the "parent" array
$completeArray = array(
"id"=> 1000,
"name"=> "Sample",
"description"=> "",
"table_id"=> 1000,
"records"=> $items
);
this should create an array with all the items and then add it to the $completeArray
Try to use $allItems[] = $item; instead of $allItems[] = array_merge($allItems, $item);

Is it possible to separate data by keys in Laravel?

From the database I get the data in the following style:
Array
(
[0] => stdClass Object
(
[id] => 2
[name] => edit_sites
)
[1] => stdClass Object
(
[id] => 1
[name] => view_sites
)
)
Does Laravel have any built-in methods for obtaining data by the keys like this:
Array
(
[id] => Array
(
[0] => 1
[1] => 2
)
[name] => Array
(
[0] => view_sites
[1] => edit_sites
)
)
or i need to do it by myself ?
Unfortunately, there is none, you have to do it by yourself albeit an easy one really.
$processedData = array();
foreach($dbData as $row) {
foreach($row as $dbKey => $value) {
$processedData[$dbKey][] = $value;
}
}
If you're getting the data back as a raw array (which you seem to be), then array_pluck will do most of what you want:
For example:
// you could use this wherever you needed the specific lists
$ids = array_pluck($results, 'id'); // [ 1, 2 ]
// or if you wanted the array exactly as asked for in the question:
$sortedArray = array(
'id' => array_pluck($results, 'id'),
'name' => array_pluck($results, 'name')
);
// [
// 'id' => [1,2],
// 'name' => [ 'view_sites', 'edit_sites' ]
// ]
If you are getting the results as some kind of Illuminate\Support\Collection class (say, from an Eloquent query), then you can use the lists method on the Collection as an alias to array_pluck
$results->lists('id'); // [ 1, 2 ]

Categories