This question already has answers here:
Convert laravel object to array
(14 answers)
Closed 5 years ago.
i queried a DB like this which got me an array:
foreach($oid as $orderid) {
$orderdetailData[] = DB::table('order_details')
->join('orders', 'order_details.oid', '=', 'orders.oid')
->select('order_details.oid', 'orders.ostatus')
->where('order_details.oid', $orderid)->get();
}
$data = array_flatten($orderdetailData);
return $data;
This is the array i get
array (size=2)
0 =>
object(stdClass)[174]
public 'oid' => int 1
public 'ostatus' => string 'Placed' (length=6)
1 =>
object(stdClass)[158]
public 'oid' => int 2
public 'ostatus' => string 'Placed' (length=6)
I am trying to get this array in the form
array (size=2)
0 =>
array (size=2)
public 'oid' => int 1
public 'ostatus' => string 'Placed' (length=6)
1 =>
array (size=2)
public 'oid' => int 2
public 'ostatus' => string 'Placed' (length=6)
I tried doing this:
foreach($orderdetailData as $key => $value){
$data[] = array_flatten($orderdetailData[$key]);
}
But doing this gets me an array in this form:
array (size=2)
0 =>
array (size=1)
0 =>
object(stdClass)[174]
public 'oid' => int 1
public 'ostatus' => string 'Placed' (length=6)
1 =>
array (size=1)
0 =>
object(stdClass)[158]
public 'oid' => int 2
public 'ostatus' => string 'Placed' (length=6)
Which is not i what i am looking for. Can someone tell me what would be an easy way to do this ? Thanks
Using array_map and casting to an array should be sufficient:
$data = array_map(function($object){
return (array) $object;
}, $data);
I also wouldn't run queries inside a loop. You should try getting that data in one query from the db. Something like this could work:
$data = DB::table('order_details')
->join('orders', 'order_details.oid', '=', 'orders.oid')
->select('order_details.oid', 'orders.ostatus')
->whereIn('order_details.oid', $oid)->get();
Edit
As it has been mentioned in another answer shortly let me explain how you can accomplish the same by setting PDO to FETCH_ASSOC:
DB::setFetchMode(PDO::FETCH_ASSOC);
$data = DB::table('order_details') .... ->get();
However this changes the fetch mode globally for the rest of the request (at least if you don't open a new connection). To be save you should change it back afterwards:
DB::setFetchMode(PDO::FETCH_ASSOC);
$data = DB::table('order_details') .... ->get();
DB::setFetchMode(PDO::FETCH_CLASS);
Or even back it up first if you can't be sure what default is used:
$fetchModeBefore = DB::getFetchMode();
DB::setFetchMode(PDO::FETCH_ASSOC);
$data = DB::table('order_details') .... ->get();
DB::setFetchMode($fetchModeBefore);
On the PDO/DB object you can set the return style to assoc.
Related
I've got told many times, if there is a new question even on the same code to just create a new thread so here I am. Thanks to the guys for helping me with the previous question.
I have the following code:
/* Return an array of _octopus_ids */
$offices = array_map(
function($post) {
return array(
'id' => get_post_meta($post->ID, '_octopus_id', true),
);
},
$query->posts
);
/* Dump out all the multi-dimensional arrays */
var_dump($offices);
$test = array_column($offices, 'id');
var_dump($test);
var_dump($offices) dumps the following:
array (size=10)
0 =>
array (size=1)
'id' => string '1382' (length=4)
1 =>
array (size=1)
'id' => string '1330' (length=4)
var_dump($test) dumps the following:
array (size=10)
0 => string '1382' (length=4)
1 => string '1330' (length=4)
Problem:
How can I use the following code:
$results = $octopus->get_all('employees/' . $test; which results in an Notice: Array to string conversion error.
I want to be able to make a results call such as this $results = $octopus->get_all('employees/1382'); - So I want just the numeric string of $test to be appended to the end of employees/
If I hardcode the 1382 after employees/, I get the following result:
object(stdClass)[1325]
public 'id' => int 1382
What's the proper way to array of strings into just strings?
This question already has answers here:
Creating one array from another array in php [closed]
(2 answers)
Closed 6 years ago.
I have the following PHP array
array (size=14)
0 =>
object(stdClass)[39]
public 'department' => string 'BOOKS' (length=32)
public 'dep_url' => string 'cheap-books' (length=32)
public 'category' => string 'Sci-fi' (length=23)
public 'cat_url' => string 'sci-fi' (length=23)
1 =>
object(stdClass)[40]
public 'department' => string 'JEWELRY' (length=32)
public 'dep_url' => string 'cheap-jewels' (length=32)
public 'category' => string 'Rings' (length=23)
public 'cat_url' => string 'rings' (length=23)
2 =>
object(stdClass)[41]
public 'department' => string 'JEWELRY' (length=32)
public 'dep_url' => string 'cheap-jewels' (length=32)
public 'category' => string 'Earings' (length=23)
public 'cat_url' => string 'cheap-earings' (length=23)
As you can see its an array of departments with their categories, how can i merge the array to get something like the following:
array (size=14)
0 =>
object(stdClass)[39]
public 'department' => string 'BOOKS' (length=32)
public 'dep_url' => string 'cheap-books' (length=32)
innerarray[0] =
public 'category' => string 'Sci-fi' (length=23)
public 'cat_url' => string 'sci-fi' (length=23)
1 =>
object(stdClass)[40]
public 'department' => string 'JEWELRY' (length=32)
public 'dep_url' => string 'cheap-jewels' (length=32)
innerarray[0] =
public 'category' => string 'Rings' (length=23)
public 'cat_url' => string 'rings' (length=23)
innerarray[1] =
public 'category' => string 'Earings' (length=23)
public 'cat_url' => string 'cheap-earings' (length=23)
I want to merge the array by department with the least amount of loops.
I hope i am clear with my question, thanks for any help you can give!
It would be best if you had a department ID (a primary key) to use to identify duplicates, but in lieu of that you should use the department name and URL together to match them.
Something like this should work:
$output = [];
foreach ($array as $entry) {
// no department ID, so create one for indexing the array instead...
$key = md5($entry->department . $entry->dep_url);
// create a new department entry
if (!array_key_exists($key, $output)) {
$class = new stdClass;
$class->department = $entry->department;
$class->dep_url = $entry->dep_url;
$class->categories = [];
$output[$key] = $class;
}
// add the current entry's category data to the indexed department
$category = new stdClass;
$category->category = $entry->category;
$category->cat_url = $entry->cat_url;
$output[$key]->categories[] = $category;
}
This will give you an array of department objects which contains, each of which contains an array of category objects. It'll be indexed by a hash which you create manually in lieu of a department ID/primary key to use instead.
To remove those keys simply do:
$output = array_values($output);
I need to create the following array from a query in codeigniter. So far what I'm producing is not what I'm looking for.
What I need...
array (size=4)
1 => string '1414277999' (length=10)
2 => string '1470411334' (length=10)
3 => string '1456617599' (length=10)
4 => string '1461538799' (length=10)
What I currently have..
array (size=4)
0 =>
object(stdClass)[35]
public 'session' => string '1' (length=1)
public 'end' => string '1477090799' (length=10)
1 =>
object(stdClass)[36]
public 'session' => string '2' (length=1)
public 'end' => string '1481932799' (length=10)
2 =>
object(stdClass)[37]
public 'session' => string '3' (length=1)
public 'end' => string '1488585599' (length=10)
3 =>
object(stdClass)[38]
public 'session' => string '4' (length=1)
public 'end' => string '1493420399' (length=10)
This is my query in codeigniter..
$bd = $this->db->select('session, end')
->from('session_dates')
->where('end >=', $now)
->get();
return $bd->result();
Can someone point me in the direction of how to build my query to create the array I'm looking for?
Although this is probably not the best way to achieve your goal, I made an object to array conversion function which I can share with you:
function (throw this into a helper file or something)
function object_to_array_recursive(&$o)
{
if(is_object($o))
{
$o = (array)$o;
}
if(is_array($o) && count($o) > 0)
{
foreach($o as $k=>&$v)
{
object_to_array_recursive($v);
}
unset($v);
}
}
Use of function
$my_db_result = $bd->result();
object_to_array_recursive($my_db_result);
return $my_db_result;
Since it accepts the parameter by reference, you will have to pass it a variable name because object_to_array_recursive($bd->result()); will fail.
You have to extract all the data you need into a new array, and then return it.
You can do this like the following :
$getEnds = function($value){ return $value->end; };
return array_map($getEnds, $bd->result());
The array_map looping the given results, and apply on each value of it the function in first parameter. This function just return the end param from current object.
You can also compress your code :
return array_map(function($value){ return $value->end; }, $bd->result());
Try this code:
$bd = $this->db->select('session, end')
->from('session_dates')
->where('end >=', $now)
->get();
$result_array = array();
foreach ($bd->result() as $row){
$result_array[$row->session] = $row->end;
}
return $result_array;
I'm building a php site and need some of the functionality provided by the blockchain API (https://github.com/blockchain/api-v1-client-php)
I'm trying to print out an overview of all transactions done to a specific address, but no success so far.
I've gathered the info of the address, but the transactions are stored in an array (as written in the documentations), and can't get them out.
$limit = 50;
$offset = 0;
$address = "xxx";
$address_info = $Blockchain->Explorer->getAddress($address, $limit, $offset);
echo $address_info->n_tx; //just as a test, this works
$transactions = $address_info->transactions; //no error here
echo $transactions->version;
The last line of code throws this error: "Trying to get property of non-object". echo $transactions[0] also doesn't work.
The github page doesn't feature any examples of printing out transactions.
The var_dump function of $transactions produces this:
array (size=2)
0 =>
object(Blockchain\Explorer\Transaction)[11]
public 'double_spend' => boolean false
public 'block_height' => int 382334
public 'time' => int 1446833376
public 'lock_time' => int 0
public 'relayed_by' => string '192.99.2.32' (length=11)
public 'hash' => string 'd9f625afe46ea8bbe9dc74484cefbcb15fbd6887a1bc619b44161114b78ab038' (length=64)
public 'tx_index' => int 109866616
public 'version' => int 1
public 'size' => int 374
public 'inputs' =>
array (size=2)
0 =>
object(Blockchain\Explorer\Input)[12]
...
1 =>
object(Blockchain\Explorer\Input)[13]
...
public 'outputs' =>
array (size=2)
0 =>
object(Blockchain\Explorer\Output)[14]
...
1 =>
object(Blockchain\Explorer\Output)[15]
...
Any ideas?
$transactions is a PHP array, not an object. You can access the version of the first object in the array using $transactions[0]->version, or iterate through the array using something like foreach ($transaction in $transactions) { ... }.
I have a problem with JSON data in PHP. I need to use data from this JSON in my SQL statement. When I'm trying to debug it with echo(var_dump, or print_r is not working too) command the output with is
{"records":"tekst","name":"[object Object]"}
This is a JSON structre:
{
records: 'tekst',
name: {
imie: 'imie1',
nazwisko: 'nazwisko1'
}
}
I'm trying to decode this by json_decode(), but I have an error
"Warning: json_decode() expects parameter 1 to be string, array
given".
Does anyone know what's wrong?
PHP manual about JSON and the format required: function.json-decode. basically, double quotes only and names must be quoted.
a demonstration of conversion using PHP.
So, you supply the json string that looks like, with the whitespace removed, like this:
{records:[{id:1,name:'n1'},{id:2,name:'n2'}]}
Which is an object containing an array with two entries that could be arrays or objects.
Except, it is not a valid JSON string as it contains single quotes. And PHP wants all the names in double quotes, as in "id":1.
So, possible PHP code to recreate that, assuming arrays as the inner entries is:
$json = new stdClass();
$records = array();
$entry = array('id' => 1, 'name' => 'n1');
$records[] = $entry;
$entry = array('id' => 2, 'name' => 'n2');
$records[] = $entry;
$json->records = $records;
$jsonEncoded = json_encode($json);
Which, when 'dump'ed looks like:
object(stdClass)[1]
public 'records' =>
array
0 =>
array
'id' => int 1
'name' => string 'n1' (length=2)
1 =>
array
'id' => int 2
'name' => string 'n2' (length=2)
Now, the string that structure produces is:
{"records":[{"id":1,"name":"n1"},{"id":2,"name":"n2"}]}
Which looks similar to yours but is not quite the same. Note the names in double quotes.
However, if your json string looked the same then PHP could decode it, as is shown below:
$jsonDecoded = json_decode($jsonEncoded);
var_dump($jsonDecoded, 'decoded');
Output: Note all objects...
object(stdClass)[2]
public 'records' =>
array
0 =>
object(stdClass)[3]
public 'id' => int 1
public 'name' => string 'n1' (length=2)
1 =>
object(stdClass)[4]
public 'id' => int 2
public 'name' => string 'n2' (length=2)
We may want arrays instead so use the true as the second parameter in the 'decode'
$jsonDecoded = json_decode($jsonEncoded, true);
var_dump($jsonDecoded, 'decoded with true switch');
Output: with arrays rather than objects.
array
'records' =>
array
0 =>
array
'id' => int 1
'name' => string 'n1' (length=2)
1 =>
array
'id' => int 2
'name' => string 'n2' (length=2)
string 'decoded with true switch' (length=24)