parse JSON data with different structures - arrays

I have a problem with accessing a certain property(hlink) in JSON code. This is because the structure of the JSON output is not always the same ,and as a result I get following error: "Cannot use object of type stdClass as array in...". Can someone help me to solve this problem?
JSON output 1 (Array)
Array (
[0] => stdClass Object (
[hlink] => http://www.rock-zottegem.be/
[main] => true
[mediatype] => webresource )
[1] => stdClass Object (
[copyright] => Rock Zottegem
[creationdate] => 20/03/2013 14:35:57
[filename] => b014933c-fdfd-4d93-939b-ac7adf3a20a3.jpg
[filetype] => jpeg
[hlink] => http://media.uitdatabank.be/20130320/b014933c-fdfd-4d93-939b-ac7adf3a20a3.jpg
)
JSON output 2
stdClass Object (
[copyright] => Beschrijving niet beschikbaar
[creationdate] => 24/04/2013 19:22:47
[filename] => Cinematek_F14281_1.jpg
[filetype] => jpeg
[hlink] => http://media.uitdatabank.be/20130424/Cinematek_F14281_1.jpg
[main] => true
[mediatype] => photo
)
And this is my code:
try {
if (!empty($img[1]->hlink)){
echo "<img src=" . $img[1]->hlink . "?maxheight=300></img>";
}
}
catch (Exception $e){
$e->getMessage();
}

Assuming this is PHP, and you know that the JSON always contains either an object or an array of objects, the problem boils down to detecting which you've received.
Try something like:
if (is_array($img)) {
$hlink = $img[0]->hlink;
} else {
$hlink = $img->hlink;
}

This isn't directly answering your question, but it should give you the means to investigate the problems you are having.
Code Sample
var obj1 = [ new Date(), new Date() ];
var obj2 = new Date();
obj3 = "bad";
function whatIsIt(obj) {
if (Array.isArray(obj)) {
console.log("obj has " + obj.length + " elements");
} else if (obj instanceof Date) {
console.log(obj.getTime());
} else {
console.warn("unexpected object of type " + typeof obj);
}
}
// Use objects
whatIsIt(obj1);
whatIsIt(obj2);
whatIsIt(obj3);
// Serialize objects as strings
var obj1JSON = JSON.stringify(obj1);
// Notice how the Date object gets stringified to a string
// which no longer parses back to a Date object.
// This is because the Date object can be fully represented as a sting.
var obj2JSON = JSON.stringify(obj2);
var obj3JSON = JSON.stringify(obj3);
// Parse strings back, possibly into JS objects
whatIsIt(JSON.parse(obj1JSON));
// This one became a string above and stays one
// unless you construct a new Date from the string.
whatIsIt(JSON.parse(obj2JSON));
whatIsIt(JSON.parse(obj3JSON));
Output
obj has 2 elements JsonExample:6
1369955261466 JsonExample:8
unexpected object of type string JsonExample:10
obj has 2 elements JsonExample:6
unexpected object of type string JsonExample:10
unexpected object of type string JsonExample:10
undefined

Related

Get Values from collection Laravel?

I have got a collection
Illuminate\Support\Collection Object ( [items:protected] =>
Array ( [0] => Array ( [url] => / [pageTitle] => Something [pageViews] => 66 ) ) )
How can I get the pageTitle and pageViews from this collection?
You need to select the first record of your collection first and then you can access its properties.
$my_collection = $my_collection->first();
//then you can do
$my_collection->pageTitle;
//or
$my_collection->pageViews;
In case it gives you can not read property of non-object take the properties as an array
$my_collection = $my_collection->first();
//then you can do
$my_collection['pageTitle'];
//or
$my_collection['pageViews'];
Thanks for the help, but I solved it.
foreach($my_collection as $key){ $key['pageTitle']}

Multiple collections in an array (session variable) — Property does not exist

I'am trying to fetch a session variable if the user is a guest. The variable is called "cart" and is set like this:
$product = new Collection((object) [
'product_id' => $request->pId,
'amount' => $request->amount,
'variations' => $variations
]);
Session::push('cart', $product);
Then I later fetch it:
if(Auth::check()){
$cartProducts = ShoppingCartItem::where('user_id', '=', Auth::user()->id)->get();
}else{
$cartProducts = Session::get('cart');
}
foreach($cartProducts as $product){
dd($product);
$totalAmount += $product->amount;
$totalPrice += (PriceHelper::getProductPrice($product->product->id, $product->amount));
}
The problem here is that dd($product) still outputs an array (the session variable array I assume) which means that for example $product->amount does not exist.
This is the output from dd($product):
You can either access the values using get():
foreach ($cartProducts as $product) {
$totalAmount += $product->get('amount');
$totalPrice += PriceHelper::getProductPrice($product->get('product_id'), $product->get('amount'));
}
or as an array:
foreach ($cartProducts as $product) {
$totalAmount += $product['amount'];
$totalPrice += PriceHelper::getProductPrice($product['product_id'], $product['amount']);
}
or you could use sum() on the collection instead of using foreach:
$cartProducts = collect(Session::get('cart'));
$totalAmount = $cartProducts->sum('amount');
$totalPrice = $cartProducts->sum(function ($product) {
return PriceHelper::getProductPrice($product['product_id'], $product['amount']);
});
Edit
For a quick fix if you need $product to be an object you could do something like:
$cartProducts = collect(Session::get('cart'))->map(function ($item) {
return (object)$item->toArray();
});
Hope this helps!

How to write/use a anorm Extractor like rowToStringSequence Column[Seq[String]]

i wrote this row converter.
implicit def rowToStringSequence: Column[Seq[String]] = Column.nonNull { (value, meta) =>
val MetaDataItem(qualified, nullable, clazz) = meta
value match {
case data: Seq[String] => Right(data)
case _ => Left(TypeDoesNotMatch(
"Cannot convert " + value + ":" + value.asInstanceOf[AnyRef].getClass +
" to String Array for column " + qualified))
}
}
Unfortunately, I do not know how to use it within a case class.
For instance:
case class profile ( eyeColor: Seq[String] )
The profile companion object:
object Profile{
val profile= {
get[Seq[String]]("eyeColor") map {
case
eyeColor => Profile(eyeColor)
}
}
}
The compilation error message is:
could not find implicit value for parameter extractor: anorm.Column[Seq[String]]
I need a hint.
Thank you!!
anorm.Column is made to convert JDBC data to desired Scala type. So first question is which kind of JDBC you want to convert as Seq[String] (not being by itself a JDBC type).

Using array for MySQL Select Statement

Apologies in advance if i use the wrong definition of a word...I am using SimpleCart to pass $.Post variables to a PHP page. If i print the array i get
Array ( [currency] => CAD [shipping] => 0 [tax] => 1.69 [taxRate] => 0.13 [itemCount] => 3 [item_name_1] => Dinner Plate [item_quantity_1] => 1 [item_price_1] => 5 [item_options_1] => code: 110 [item_name_2] => Side Plate [item_quantity_2] => 1 [item_price_2] => 4 [item_options_2] => code: 125 [item_name_3] => Mixing Bowl [item_quantity_3] => 1 [item_price_3] => 4 [item_options_3] => code: 66 )
What I am struggling with (and going around in circles) is a method to do the following..
Explode the [item_options] variable to strip out the CODE: part of the value and just leave the numeric section.
concatenate these values into a string so i can use a SELECT statement to only pull records that have an ID passed in the [item.options].
I understand how to explode a single parameter, but cannot work out how to loop through the array, explode the key and create the value i need for the SQL.
Any help or pointers to relevant tutorials would be much appreciated
$codes = array();
foreach ($_POST as $key => $value) { // Loop through the $_POST array
if (preg_match('/^item_options_/', $key)) { // And validate the value
$item_arr = explode(' ', $value);
$item_id = $item_arr[1]; // Get the ID number from the value
if (is_numeric($item_id)) { // Validate it
$codes[] = $item_id; // Add it to the array we're building
}
}
}
$codes_string = implode(', ', $codes); // Concatenate them into a string that can be used in a SQL IN clause
$sql = "SELECT * from table WHERE id IN ($codes_string)"; // Build the SQL

Add an array to a session array

I have an array from a MySQL query of ID numbers that I'm trying to add to a Session Array that is already created. For some reason, my code is adding an array inside the Session Array already in place rather than just adding the ID numbers to the Session. What is causing this to happen?
Here is my PHP...
//Find members of this group and create an array to add to cart
$deletedgroupmembersquery = "SELECT * FROM groupmember WHERE group_id='$groupid'";
$deletedgroupmembers = mysql_query($deletedgroupmembersquery) or die('SQL Error :: '.mysql_error());
if (mysql_num_rows($deletedgroupmembers) > 0) {
$groupmembers = mysql_num_rows($deletedgroupmembers);
$cart = array();
while(($deletedmembersrow = mysql_fetch_assoc($deletedgroupmembers))) {
$cart[] = $deletedmembersrow['contact_id'];
}
//Add the array to the cart session
if (isset($cart)) {
$_SESSION['cart'] = array();
array_push($_SESSION[cart],$cart);
} else {
}
Here is the session the above code is creating..
Array ( [cart] => Array ( [0] => Array ( [0] => 1362 [1] => 1371 [2] => 2241 ) )
Thanks for any help.
$cart is already an array. When you do:
array_push($_SESSION[cart],$cart);
you're pushing it as a sub-array of $_SESSION['cart']. I think you just want:
$_SESSION['cart'] = $cart;
You're defining $cart as an array before you push it into $_SESSION[cart]...so you're pushing an array into an array. Try something like this:
if (!empty($cart)) {
$_SESSION['cart'] = array();
foreach ($cart AS $item) {
array_push($_SESSION['cart'], $item);
}
}
You can also just place the array_push inside your while(), and stick the $_SESSION['cart'] = array() before the while(), and it will achieve the same thing.

Resources