How to extract data from JSON - Laravel & JSON - php

This is how my json looks like ["Chicken",{"quantity":"1"},"Froggies",{"quantity":"2"},"Fryies",{"quantity":"3"}].
Is there a way that i can get the data out the results like
Chicken : 1, Froggies:2, Fryies:3
I tried to use implode to get this done but i get an error saying array to string conversion,
Below is my code
foreach($request->get('item_id') as $key => $id)
{
$selected_item = Item::all()->where('id',$id);
foreach($selected_food as $select)
{
$food_selected[]= $select->name ;
$food_selected[] = ['quantity' => $request->get('quantity')[$key]];
}
}
$query ="Your items are ".implode(',',$food_selected)."";

Maybe array of objects would be more useful in that situation, which you could get this way:
$arr = [];
foreach ( $request->get('item_id') as $key => $id ) {
$selected_item = Item::all()->where('id', $id);
foreach ( $selected_item as $select ) {// $selected_item or $selected_food here
/*
$obj = new stdClass;
$obj->{$select->name} = $request->get('quantity')[$key];
$arr[] = $obj;*/
$arr[$select->name] = (int) $request->get('quantity')[$key];
}
}
$query = '';
foreach ( $arr as $k => $v ) {
$query .= ' '.$k.': '.$v.',';
}
$query = rtrim($query, ',');
$query = ltrim($query);
$query = "Your items are ".$query;

I assume that the ID is unique key for an Item and your Item::all()->where('id',$id) will return only one record. If this is true, the second loop is unnecessary.
Based on this assumption, I come to this code:
$result = collect($request->get('item_id'))
->map(function($itemId, $itemKey) use ($request) {
$item = Item::find($itemId);
return $item->name . ' : ' . $request->get('quantity')[$itemKey];
})->implode(',');
// $result contains the string: "Chicken : 2, Fries : 1"
For explanation:
Cast the array into a collection
Use map to loop over it
Find the Item by its ID
Return the name and the quantity (this returns a collection)
Implode the collection

Related

How to get data from database that result as an array in model codeigniter

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;
}

get value of an element inside an associative array from a table

$arr = ['b1' => 'banners/5B5C4965B9A50.jpg', 'vid' => 'vid.mp4', 'linked' => 'linkedabc'];
I inserted the above array into a table (using json_encode) so the content of the filed named map is:
{"b1":"banners/5B5C4965B9A50.jpg","vid":"vid.mp4","linked":"linkedabc"}
Now I want to get and loop this array:
$sql = "select map from params where what = 'artb'";
$st = $db->prepare($sql);
$st->execute();
$arrx = $st->fetch();
//$arrx = json_decode($arrx); - also tried here
foreach($arrx as $key => $el){
if($key == 'b1') {getb1($el);}
}
function getb1($el){
echo $el;
}
Result:
{"b1":"banners/5B5C4965B9A50.jpg","vid":"vid.mp4","linked":"linkedabc"}
I'm expecting banners/5B5C4965B9A50.jpg.
What's wrong?
$arrx = json_decode($arrx,true);
foreach($arrx as $key => $el){
if($key == 'b1') {getb1($el);}
}
You need an array before you loop it. You try to access a json object the way you access array which is not possible.
Your code will work perfect after that.
$data = '{"b1":"banners/5B5C4965B9A50.jpg","vid":"vid.mp4","linked":"linkedabc"}';
$arrx = json_decode($data,true);
foreach($arrx as $key => $el){
if($key == 'b1') {getb1($el);}
}
function getb1($el){
echo $el;
}
And the output is banners/5B5C4965B9A50.jpg as expected
Do json_decode first and then access the key directly.
$arrx = json_decode($arrx['map']);
To access b1,
echo $arrx->b1;
Your updated code snippet will look like this,
$sql = "select map from params where what = 'artb'";
$st = $db->prepare($sql);
$st->execute();
$arrx = $st->fetch();
foreach($arrx as $key => $el){
$elMap = json_decode($el['map']);
echo $elMap->b1;
}

'where' like querying an array or object

[{"id":1,"username":"example","email":"example#gmail.com","password":"example123","created_at":"2015-01-13 11:39:24","updated_at":"2015-01-13 11:39:24"},
{"id":2,"username":"ex2","email":"ex#ex.com","password":"example","created_at":"2015-01-13 11:39:02","updated_at":"2015-01-13 11:39:02"}]
I got an object like above. The thing I want to is select the object that's id is 1 for example. Like
select * from object where id=1
with SQL
How to do it?
I hope i got your question right.
Try the following
<?php
$array = json_decode('[{"id":1,"username":"example","email":"example#gmail.com","password":"example123","created_at":"2015-01-13 11:39:24","updated_at":"2015-01-13 11:39:24"},
{"id":2,"username":"ex2","email":"ex#ex.com","password":"example","created_at":"2015-01-13 11:39:02","updated_at":"2015-01-13 11:39:02"}]');
foreach( $array as $v ) {
if( $v["id"] == 1 ) {
echo "I am ID 1";
break;
}
}
Decode your object (http://php.net/manual/it/function.json-decode.php) and then traverse your array with a foreach checking the id value inside of it with an if statement.
$obj_to_array = json_decode($json_object);
$target = '';
foreach($obj_to_array as $row){
if($row['id'] == 1)
$target = $row;
}
// $target holds your row with id = 1
$data = '[{"id":1,"username":"example","email":"example#gmail.com","password":"example123","created_at":"2015-01-13 11:39:24","updated_at":"2015-01-13 11:39:24"},
{"id":2,"username":"ex2","email":"ex#ex.com","password":"example","created_at":"2015-01-13 11:39:02","updated_at":"2015-01-13 11:39:02"}]';
$data = json_decode($data);
$id = 1;
$key = 'id';
$data = array_filter(
$data,
function($value) use ($key, $id) {
return ($value->$key == $id);
}
);
var_dump($data);
Decode the object using json_decode. Use the code below
<?php
$json='[{"id":1,"username":"example","email":"example#gmail.com","password":"example123","created_at":"2015-01-13 11:39:24","updated_at":"2015-01-13 11:39:24"},
{"id":2,"username":"ex2","email":"ex#ex.com","password":"example","created_at":"2015-01-13 11:39:02","updated_at":"2015-01-13 11:39:02"}]';
$p = json_decode($json,true);
$l=count($p);
for($i=0;$i<=$l;$i++){
$id=$p[$i]["id"];
if($id==1){
print_r($p[$i]); // WIll print the id if 1
}
}
Hope this helps you

PHP list to an Array to a foreach Joomla Module

I have the following PHP, that needs to take a list of article ids and run it through a function to get them all from the database.
I am very much a beginner in PHP so far I have:
list($slide1, $slide2, $slide3, $slide4, $slide5) = explode(" ", $params->get('id'));
$a = array(
$item => $slide1,
"two" => $slide2,
// "three" => $slide3,
// "four" => $slide4,
// "five" => $slide5
);
foreach ($a as $k) {
$args['id'] = $k;
$item = ModArticleSlider::getArticles($args);
}
and the class:
class ModArticleSlider {
public function getArticles($args){
$db = &JFactory::getDBO();
$item = "";
$id = $args['id'];
if($id > 0){
$query = "select * ";
$query .= "FROM #__content WHERE id =".$id." AND state=1 " ;
//echo $query;
$db->setQuery($query);
$item = $db->loadObject();
}
return $item;
}
}
How would i get it so that instead of specifying $item to have it almost dynamic so that i can get all the selected articles and place them in different variables.. or would i have to place them in a array?
Any Advice/Answers Greatly Appreciated.
Another approach, and possibly more performant as it would require only one database query (versus one for each article), would be to use http://docs.joomla.org/JDatabase::loadObjectList
So, you could instead pass an array of your articles ids as $ids to your class like:
public function getArticles($ids){
if ($ids) {
$db = JFactory::getDbo();
$query = "SELECT * FROM #__content WHERE id IN (" . implode(',', $id) . ") AND state=1 " ;
$db->setQuery($query);
$rows = $db->loadObjectList();
return $rows;
}
return FALSE;
}
$rows is returned as an array so you can then process it as needed.
i am also beginner of PHP.
Please Try this:
foreach ($a as $k => $val) {
$args = $val;
$item[] = ModArticleSlider::getArticles($args);
var_dump($item);
}
in your class
simply
$id = $args;
i hope it will help you!
Store the articles into an array, you can try this:
$slides = explode(" ", $params->get('id'));
$articleArray = array();
foreach($slides as $slide) {
$articleArray[] = ModArticleSlider::getArticles($slide);
}
var_dump($articleArray);

array to string php

Hy every one I have this problem with an array I start like this...
$name = array($_POST['names']);
$nameId = array();
$query = mysql_query("SELECT id FROM types WHERE find_in_set (name, '$name')");
while($row = mysql_fetch_assoc($query)){
$nameId[] = array('ids' => $row['id'] );
}
which gives me arrays like this..
$name:
array('0'=>'name1,name2,name3')
$names:
array('0'=>array('ids'=>'61'), '1'=>array('ids'=>'6'), '2'=>array('ids'=>'1'))
how can I bring this in an string/form like this..
array('0'=>'61,6,1')
The idea is to save the ids to the Database.
Or is the a better more efficent way to get names from a form compare them with a database and get the ids back to save them to the Database?
many thanks in advance.
Change your assignment to this:
$nameId[] = $row['id'];
$name = array(name1,name2,name3);
$nameId = array();
$query = mysql_query("SELECT id FROM types WHERE find_in_set (name, '$name')");
while($row = mysql_fetch_assoc($query)){
//below line changed
$nameId[] = $row['id'] ;
}
$string = implode(',',$nameId);
Try this :
$array = array(0=>array(0=>'61'),1=>array(0=>'6'),2=>array(0=>'1'));
$result = implode(",",call_user_func_array('array_merge', $array));
Please note : Here all are numeric keys, so change your code to :
$nameId[] = array($row['id'] ); , remove key 'ids' from here
Output :
61,6,1
Thats what I think
$nameId[] = $row['id'];
$stringId = implode(',',$name);
Use following function that will loop through array and find ids key and merge it into other array and after that when you calling this function it will impload it.
function CustomFindJoinArray( $needly, $array )
{
$results = array();
foreach ( $array as $key => $value )
{
if ( is_array( $value ) )
{
$results = array_merge($results, foo( $needly, $value ));
}
else if ( $key == $needly )
{
$results[] = $value;
}
}
return $results;
}
echo implode( ",", CustomFindJoinArray( "ids", $your_array ) );
where $your_array will be array('0'=>array('ids'=>'61'), '1'=>array('ids'=>'6'), '2'=>array('ids'=>'1'))
OR More simple
foreach ($your_array as $key => $ids) {
$newArray[] = $array[$key]["ids"];
}
$string = implode(',', $newArray);
$ids = array();
foreach($nameId as $curr) {
$ids[] = $curr['ids'];
}
$str = "(".implode(",",$ids).")";

Categories