Simple question to which I don't have an answer.
How can I change my array from this:
[{"sku":"6"},{"buyers":"7"},{"base":"8"}]
to this:
[{"sku":"6","buyers":"7","base":"8"}]
I have three queries for three different database tables:
$sku = DB::table('mapiranje')->select(DB::raw('count(*) as sku'))
->where('mate_fk', '=', NULL)
->get();
$kupac = DB::table('mapkupci')->select(DB::raw('count(*) as buyers'))
->where('kupci_fk', '=', NULL)
->get();
$base = DB::table('dist_base')->select(DB::raw('count(*) as base'))
->where('base_fk', '=', NULL)
->get();
now each returns:
[{"sku":"6"}]
[{"buyers":"6"}]
[{"base":"6"}]
I have used merge_array to make a single array, but I get:
[{"sku":"6"},{"buyers":"7"},{"base":"8"}]
what I want is:
[{"sku":"6","buyers":"7", "base":"8"}]
Refactor your code according to right Laravel way:
$result = [
'sku' => DB::table('mapiranje')->whereNull('mate_fk')->count(),
'buyers' => DB::table('mapkupci')->whereNull('kupci_fk')->count(),
'base' => DB::table('dist_base')->whereNull('base_fk')->count()
];
$result = [];
foreach($input as $oneInputRow) {
$result[$oneInputRow[0]] = $oneInputRow[1];
}
$target = array();
$start = array(array("sku"=>"6"), "buyers"=>"7"), "base"=>"8"));
foreach($start as $sub){
foreach($sub as $key => $val){
$target[$key] = $val;
}
}
Not shure if laravel provides any special syntax, but just with php I'd do it as above.
Basicly you loop over the start-array. In that you loop over every array to get the key/val combination and put that into the target-array.
For the second loop there would be other ways if you only have one entry in every secondary array.
Please try below code
$dd = '[{"sku":"6"},{"buyers":"7"},{"base":"8"}]';
$data = json_decode($dd,true);
$result = array();
foreach($data as $key=>$value){
foreach($value as $key1=>$value1){
$result[$key1] = $value1;
}
}
echo json_encode($result); //this will print your required format result
Related
I got a few parameters in the url that I want to loop into a Laravel where query. After doing that I want to merge them into 1 collection and without duplicates.
This is what I have written already:
foreach($request->query() as $key => $query){
$guides[] = SupportGuideTranslation::where($key, $query)->get();
}
These are my parameters:
?active=1&language_id=2
Your current code executes one query per parameter/condition. You could do:
$query = SupportGuideTranslation::query();
foreach($request->query() as $key => $value){
$query->where($key, $value);
}
$guides = $query->get();
I would also advise you to check that the parameter actually exists on the table before adding it to the query. If I make a request with active=1&non_existing_column=2 your code would throw an error.
$guides = new Collection;
foreach($request->query() as $key => $value){
if($guides->isEmpty()){
$guides = SupportGuideTranslation::where($key, $value)->get();
}
else{
$guides = $guides->toBase()->merge(SupportGuideTranslation::where($key, $value)->get());
}
}
$guides = $guides->unique();
where() can take an array. So you don't necessarily need to loop:
SupportGuideTranslation::where($request->query())->get();
If that doesn't work for you and you have to loop over the query params, that might help:
$guides = new Collection;
foreach($request->query() as $key => $query){
$guides = $guides->merge(SupportGuideTranslation::where($key, $query)->get());
}
$guides = $guides->unique();
I want to make a query that results like this in codeigniter MODEL:
$caldata = array (
15 => 'yes',
17 => 'no'
);
Is that possible to do?
Take NOTE: The 15,17 and yes,no are in the same database table.
There is no core helper function to achieve what you want in CI. But you can create your own helper function:
function pluck($arr = [], $val = '', $key = '')
{
// val - label for value in array
// key - label for key in array
$result = [];
foreach ($arr as $value) {
if(!empty($key)){
$result[$value[$key]] = $value[$val];
}else{
$result[] = $value[$val];
}
}
return $result;
}
you can use result_array() function so you can have something like:
$query = $this->db->select('id,answer')->from('users')->get();
$result = $query->result_array();
print_r($result);
After that you have your array and you can make the $key => $value relation of the fields
After a long search i found an answer. Sample way to do this:
$query = $this->db->select('start_date, class')->from('event')->like('start_date', "$year-$month", 'after')->get();
$datavariable = $query->result();
$caldata = array();
foreach($datavariable as $row){
$caldata[substr($row->start_date,8,2)] = $row->class;
}
I'm trying to write a function that do the following :
Let's say i have an array :
$data = array(
array('10','15','20','25'),
array('Blue','Red','Green'),
array('XL','XS')
)
and my result array should be like :
$result = array(
array('10','15','20','25'),
array('Blue','Red','Green','Blue','Red','Green','Blue','Red','Green','Blue','Red','Green')
array('XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS','XL','XS')
)
Im stuck with this because i want a function that is able to do this no matter how much array there is in the first array $data
I have only been able to write this, which is what give the $result array :
foreach($data[2] as $value2){
$result[2][] = $value2;
foreach($data[1] as $value1){
$result[1][] = $value1;
foreach($data[0] as $value0){
$result[0][] = $value0;
}
}
}
After a few research, it seems that a recursive function is the way to go in order to dynamically generate those foreach but i can't get it to work.
Thanks for your help.
This is dynamic:
$result[] = array_shift($data);
foreach($data as $value) {
$result[] = call_user_func_array('array_merge',
array_fill(0, count($result[0]), $value));
}
Get and remove the first element from original
Loop remaining elements and fill result with values X number of values in first element
Since the elements were arrays merge them all into result
If modifying the original is unwanted, then use this method:
$result[] = reset($data);
while($value = next($data)) {
$result[] = call_user_func_array('array_merge',
array_fill(0, count($result[0]), $value));
}
just use array_fill and array_merge functions
$result = array(
$data[0],
array_merge(...array_fill(0,count($data[0]), $data[1])),
array_merge(...array_fill(0,count($data[0])*count($data[0]), $data[2]))
);
print_r($result);
demo on eval.in
here is what I'm trying to do. I'm retrieving information from a database via array. What is happening is the information from the previous array is going into the next array.
Here is the code:
$i = 0;
foreach ($array_name as $key => test_name) {
$id = $test_name['id']
foreach ($test_name['id] as $key => $test_id {
$data = ModelClass::Information($test_id);
$array_name[$i]['new_infroamtion'] = $data'
}
}
So right now based on the code data from the table is correctly going into the first array, however, information based from the first array is going into the second array..
Let me know if you need anymore information.
Thank you
You are using $array_name while you are iterating through $array_name. This is valid code if you want to do this, but I don't think you do. You need to change the second $array_name to something else.
$i = 0;
foreach (**$array_name** as $key => test_name) {
$id = $test_name['id']
foreach ($test_name['id'] as $key => $test_id {
$data = ModelClass::Information($test_id);
**$array_name**[$i]['new_infroamtion'] = $data
}
}
I did find a solution. What I had to do was add the following
$s = array()
Then in the for loop, I added the following code:
foreach ($test_name['id] as $key => $test_id {
$data = ModelClass::Information($test_id);
$s[] = $data
$array_name[$i]['new_infroamtion'] = $s'
}
I got stuck somehow on the following problem:
What I want to achieve is to merge the following arrays based on key :
{"Entities":{"submenu_id":"Parents","submenu_label":"parents"}}
{"Entities":{"submenu_id":"Insurers","submenu_label":"insurers"}}
{"Users":{"submenu_id":"New roles","submenu_label":"newrole"}}
{"Users":{"submenu_id":"User - roles","submenu_label":"user_roles"}}
{"Users":{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}}
{"Accounting":{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}}
Which needs to output like this:
[{"item_header":"Entities"},
{"list_items" :
[{"submenu_id":"Parents","submenu_label":"parents"},
{"submenu_id":"Insurers","submenu_label":"insurers"}]
}]
[{"item_header":"Users"},
{"list_items" :
[{"submenu_id":"New roles","submenu_label":"newrole"}
{"submenu_id":"User - roles","submenu_label":"user_roles"}
{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}]
}]
[{"item_header":"Accounting"},
{"list_items" :
[{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}]
}]
I have been trying all kinds of things for the last two hours, but each attempt returned a different format as the one required and thus failed miserably. Somehow, I couldn't figure it out.
Do you have a construction in mind to get this job done?
I would be very interested to hear your approach on the matter.
Thanks.
$input = array(
'{"Entities":{"submenu_id":"Parents","submenu_label":"parents"}}',
'{"Entities":{"submenu_id":"Insurers","submenu_label":"insurers"}}',
'{"Users":{"submenu_id":"New roles","submenu_label":"newrole"}}',
'{"Users":{"submenu_id":"User - roles","submenu_label":"user_roles"}}',
'{"Users":{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}}',
'{"Accounting":{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}}',
);
$input = array_map(function ($e) { return json_decode($e, true); }, $input);
$result = array();
$indexMap = array();
foreach ($input as $index => $values) {
foreach ($values as $k => $value) {
$index = isset($indexMap[$k]) ? $indexMap[$k] : $index;
if (!isset($result[$index]['item_header'])) {
$result[$index]['item_header'] = $k;
$indexMap[$k] = $index;
}
$result[$index]['list_items'][] = $value;
}
}
echo json_encode($result);
Here you are!
In this case, first I added all arrays into one array for processing.
I thought they are in same array first, but now I realize they aren't.
Just make an empty $array=[] then and then add them all in $array[]=$a1, $array[]=$a2, etc...
$array = '[{"Entities":{"submenu_id":"Parents","submenu_label":"parents"}},
{"Entities":{"submenu_id":"Insurers","submenu_label":"insurers"}},
{"Users":{"submenu_id":"New roles","submenu_label":"newrole"}},
{"Users":{"submenu_id":"User - roles","submenu_label":"user_roles"}},
{"Users":{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}},
{"Accounting":{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}}]';
$array = json_decode($array, true);
$intermediate = []; // 1st step
foreach($array as $a)
{
$keys = array_keys($a);
$key = $keys[0]; // say, "Entities" or "Users"
$intermediate[$key] []= $a[$key];
}
$result = []; // 2nd step
foreach($intermediate as $key=>$a)
{
$entry = ["item_header" => $key, "list_items" => [] ];
foreach($a as $item) $entry["list_items"] []= $item;
$result []= $entry;
}
print_r($result);
I would prefer an OO approach for that.
First an object for the list_item:
{"submenu_id":"Parents","submenu_label":"parents"}
Second an object for the item_header:
{"item_header":"Entities", "list_items" : <array of list_item> }
Last an object or an array for all:
{ "Menus: <array of item_header> }
And the according getter/setter etc.
The following code will give you the requisite array over which you can iterate to get the desired output.
$final_array = array();
foreach($array as $value) { //assuming that the original arrays are stored inside another array. You can replace the iterator over the array to an iterator over input from file
$key = /*Extract the key from the string ($value)*/
$existing_array_for_key = $final_array[$key];
if(!array_key_exists ($key , $final_array)) {
$existing_array_for_key = array();
}
$existing_array_for_key[count($existing_array_for_key)+1] = /*Extract value from the String ($value)*/
$final_array[$key] = $existing_array_for_key;
}