Laravel 5.2 get value field only in json response - php

Here is my code
$temp = $this->whereBetween('id', [$sid,$eid])
->select('id','temperature')
->get();
will return
[{"id":1,"temperature":34.5},{"id":2,"temperature":32.56},
how do i get only result like this, remove the key and pass the value only.
[{1,34.5},{2,32.56}]
I have using lists but it only return partial or all field.

You need to rebuild the array. I've tested this code and it works:
$array = [];
foreach($temp as $k => $v) {
$array[] = [$v['id'], $v['temperature']];
}
After that just serialize this array or use as is.

The function that you search, is array_values.
Iterate over your array, use that function, and save it back to an array.
For example:
$newArray = array();
foreach ($temp as $row) {
$newArray[] = array_values($row);
}

Related

How to get single dimensional array from two dimensional array in php/laravel?

I am doing laravel project. I have one sql query as,
$catcount=2;
for($i=0;$i<$catcount;$i++) {
$subCat[] = Category::where('parent_id', '=', $userCategory[$i])->pluck('id');
}
$subCat returns an array as,
[[54,55,56,57,58],[48,49,50,51,52]]
I want this array as a single dimensional array like,
[54,55,56,57,58,48,49,50,51,52]
I am not getting how to do this, Please help and thanks in advance.
I suggest You to do ids merge before querying, so You will save some run time by accessing database only one time.
$catcount = 2;
$parents_ids = [];
for ($i = 0; $i < $catcount; $i++) {
$parents_ids[] = $userCategory[$i];
}
$subCats = Category::whereIn('parent_id', $parents_ids)->pluck('id');
$catcount=2;
for($i=0;$i<$catcount;$i++) {
$subCat[] = Category::where('parent_id', '=' $userCategory[$i])->pluck('id');
}
array_merge($subCat[0],$subCat[1]);
From your final array, you can just do an array merge
list($a1, $a2) = $subCat;
$subCat = array_merge($a1, $a2);
There are a lot of ways to do that. One of them: simple, but universal, readable and updatable (if something will change in your data structure, you'll be able to update this code in no time):
$newArr = [];
foreach ($subCat as $subArr) {
foreach ($subArr as $value) {
$newArr[] = $value;
}
}
if your array have multiple elements, you can merge them using this code:
$subCats = call_user_func_array("array_merge", $subCat);

How to declare, insert and iterate a php associative array with an associative array as value?

I need to work with a hashtable which values can store variables like:
$numberOfItems
$ItemsNames
If I ain't wrong, that would mean another hash like array as value.
What should be the right syntax for inserting and iterating over it?
Is anything like:
$hash['anyKey']=>$numberOfItems=15;
$hash['anyKey']=>$ItemsNames=['f','fw'];
valid?
if there's no chance to have collusion in item name, you can use the name in key
$hash[$ItemsName] = $numberOfItems;
in the other case, use an integer for example as a key, then the different "attributes" you want as keys for the 2nd array
$hash[$integer]["count"] = $numberOfItems;
$hash[$integer]["name"] = $name;$
Then, for iterating (1st case):
foreach ($hash as $name => $number) {
echo $number;
echo $name;
}
or, 2nd case
foreach ($hash as $item) {
echo $item["name"];
echo $item["count"];
}
To create php array, which can be a hash table, you can do:
$arr['element'] = $item;
$arr['element'][] = $item;
$arr['element'][]['element'] = $item;
Other way:
$arr = array('element' => array('element' => array(1)));
To iterate over it use foreach loop:
foreach ($items as $item) {
}
It's also possible to create nested loops.
About your case:
$hash['anyKey']=>$numberOfItems=15;
$hash['anyKey']=>$ItemsNames=['f','fw'];
I would do:
$hash['anyKey']['numberOfItems'] = 15;
$hash['anyKey']['ItemsNames'] = array('f','fw');

php arrays: search for matching values in a table and replace with array keys

Please i want to loop through my table and compare values with an array in a php included file. If there is a match, return the array key of the matched item and replace it with the value of the table. I need help in returning the array keys from the include file and comparing it with the table values.
$myarray = array(
"12aaa"=>"hammer",
"22bbb"=>"pinchbar",
"33ccr"=>"wood" );
in my loop in a seperate file
include 'myarray.inc.php';
while($row = $db->fetchAssoc()){
foreach($row as $key => $val)
if $val has a match in myarray.inc.php
{
$val = str_replace($val,my_array_key);
}
}
So in essence, if my db table has hammer and wood, $val will produce 12aaa and 3ccr in the loop. Any help? Thanks a lot
You are looking for array_search which will return the key associated with a given value, if it exists.
$result = array_search( $val, $myarray );
if ($result !== false) {
$val = $result;
}
your array should look like
$myarray = array(
"hammer"=>"11aaa",
"pinchbar"=>"22bbb",
"wood"=>"33ccr" );
and code
if (isset($myarray[$key])){
//do stuff
}
I think you need the function in_array($val, $myarray);
If you don't want or can't change $myarray structure like #genesis proposed, you can make use of array_flip
include 'myarray.inc.php';
$myarray = array_flip($myarray);
while($row = $db->fetchAssoc()) {
foreach($row as $key => $val) {
if (isset($myarray[$val])) {
// Maybe you should use other variable instead of $val to avoid confusion
$val = $myarray[$val];
// Rest of your code
}
}
}

Adding an item to an associative array

//go through each question
foreach($file_data as $value) {
//separate the string by pipes and place in variables
list($category, $question) = explode('|', $value);
//place in assoc array
$data = array($category => $question);
print_r($data);
}
This is not working as it replaces the value of data. How can I have it add an associative value each loop though? $file_data is an array of data that has a dynamic size.
You can simply do this
$data += array($category => $question);
If your're running on php 5.4+
$data += [$category => $question];
I think you want $data[$category] = $question;
Or in case you want an array that maps categories to array of questions:
$data = array();
foreach($file_data as $value) {
list($category, $question) = explode('|', $value, 2);
if(!isset($data[$category])) {
$data[$category] = array();
}
$data[$category][] = $question;
}
print_r($data);
Before for loop:
$data = array();
Then in your loop:
$data[] = array($catagory => $question);
I know this is an old question but you can use:
array_push($data, array($category => $question));
This will push the array onto the end of your current array. Or if you are just trying to add single values to the end of your array, not more arrays then you can use this:
array_push($data,$question);
For anyone that also need to add into 2d associative array, you can also use answer given above, and use the code like this
$data[$category]["test"] = $question
you can then call it (to test out the result by:
echo $data[$category]["test"];
which should print $question

Make 1d Array from 1st member of each value in 2d Array | PHP

How can you do this? My code seen here doesn't work
for($i=0;i<count($cond);$i++){
$cond[$i] = $cond[$i][0];
}
It can be as simple as this:
$array = array_map('reset', $array);
There could be problems if the source array isn't numerically index. Try this instead:
$destinationArray = array();
for ($sourceArray as $key=>$value) {
$destinationArray[] = $value[0]; //you may want to use a different index than '0'
}
// Make sure you have your first array initialised here!
$array2 = array();
foreach ($array AS $item)
{
$array2[] = $item[0];
}
Assuming you want to have the same variable name afterwards, you can re-assign the new array back to the old one.
$array = $array2;
unset($array2); // Not needed, but helps with keeping memory down
Also, you might be able to, dependant on what is in the array, do something like.
$array = array_merge(array_values($array));
As previously stated, your code will not work properly in various situation.
Try to initialize your array with this values:
$cond = array(5=>array('4','3'),9=>array('3','4'));
A solution, to me better readable also is the following code:
//explain what to do to every single line of the 2d array
function reduceRowToFirstItem($x) { return $x[0]; }
// apply the trasnformation to the array
$a=array_map('reduceRowTofirstItem',$cond);
You can read the reference for array map for a thorough explanation.
You can opt also for a slight variation using array_walk (it operate on the array "in place"). Note that the function doesn't return a value and that his parameter is passed by reference.
function reduceToFirstItem(&$x) { $x=$x[0]; }
array_walk($cond, 'reduceToFirstItem');
That should work. Why does it not work? what error message do you get?
This is the code I would use:
$inArr;//This is the 2D array
$outArr = array();
for($i=0;$i<count($inArr);$i++){
$outArr[$i] = $inArr[$i][0];
}

Categories