Codeigniter array to object conversation - php

I am getting this error "Trying to get property of non-object" for lines
'price' => $product->product_price,
'name' => $product->product_name
for doing in the same page
function remove($rowid) {
$this->cart->update(array(
'rowid' => $rowid,
'qty' => 0
));
}
i can solve this problem, by doing like, 'price' => $product['product_price'],Bus as my other page using 'price' => $product->product_pricethem as fine, so i dont want to convert it to array,
my question is how can i convert $this->cart->update(array( to an object so that, these lines
'price' => $product->product_price,
'name' => $product->product_name
works fine for object?
Thanks in advance.

$Arr = array(
'rowid' => $rowid,
'qty' => 0
);
$Obj = (object)$Arr;
This is conversion of Array to Object. Do you want it?

You assign the result to an array. Then you try to use the array as an object. Next, the returned result is an array as well which you try to use as a object.
The smarter ways you can convert array into object
From PHP manual:
<?php
$literalObjectDeclared = (object) array(
'foo' => (object) array(
'bar' => 'baz',
'pax' => 'vax'
),
'moo' => 'ui'
);
print $literalObjectDeclared->foo->bar; // outputs "baz"!
?>
little genius hack:
<?php
// assuming $var is a multidimensional array
$obj = json_decode (json_encode ($var), FALSE);
?>
So you can convert by casting array into object:
<?php
$array = array(
// ...
);
$object = (object) $array;
?>
if you want manual way you can do this:
<?php
$object = object;
foreach($arr as $key => $value)
{
$object->{$key} = $value;
}
?>

Define $product as a new standard class:
$product = new stdClass();

Related

Issue with the loop foreach php

sorry if my question seems stupid, I'm new to php.
I try to create a loop on my array but the loop returns me only the last value.
I don't understand and I tried everything
$categories = array('name' => 'mamals', 'id' => '1');
$categories = array('name' => 'birds','id' => '2');
$categories = array('name' => 'fishs', 'id' => '3');
$categories = array('name' => 'reptiles', 'id' => '4');
$category = $categories;
foreach($category as $key =>$categ){
echo $categ;
}
It return only "reptiles 4" !
Thank you for you answers
You are overwriting the variable categories, i modified the code by initializing the categories with an empty array, then pushing your entries in it.
$categories = [];
array_push($categories, array('name' => 'mamals', 'id' => '1'));
array_push($categories, array('name' => 'birds','id' => '2'));
array_push($categories, array('name' => 'fishs', 'id' => '3'));
array_push($categories, array('name' => 'reptiles', 'id' => '4'));
foreach($categories as $key=>$categ){
echo "ID: " . $categ["id"] . ", NAME: " . $categ["name"];
}
I response to shunz19's anwser where I said:
It would help to show the shorthand for this mechanism as well. I don't think anyone would use array_push in this sitation.
Here is a more concise solution:
Cause:
You are overwriting your variable - $categories - each time you use =.
So after line 3 the only value in $categories is :
categories = array('name' => 'reptiles', 'id' => '4');
Step By Step:
You look like you want to be adding entries to the Categories multidimensional array. Therefore you need to tell PHP to add not to overwrite, typically with the [] indicating the value is to be inserted into a new (incremental) variable key.
$categories = array('name' => 'mamals', 'id' => '1');
$categories[] = array('name' => 'birds','id' => '2');
This will increment the key index (numeric) by 1 and set the value of array into that key.
It is standard practise to establish numeric arrays and then populate them with this style of referencing.
But this isn't quite simple...
Because your parent array contains sub-arrays, your foreach will give warnings and errors because:
Warning: Array to string conversion in /home/user/scripts/code.php on line XX
Can you see why?
Yes, because your foreach is only opening the parent array, not the child arrays so the data types within are still arrays, but you want to output them as if they're strings.
How can you do this? With a fun little function called print_r().
Concise Solution and Fix:
$categories = []; // Establish the var type is an array.
$categories[] = array('name' => 'mamals', 'id' => '1'); // Add to the array.
$categories[] = array('name' => 'birds','id' => '2'); // add more,...
$categories[] = array('name' => 'fishs', 'id' => '3');
$categories[] = array('name' => 'reptiles', 'id' => '4');
$category = $categories;
foreach($category as $key =>$categ){
print_r($categ);
}
Output:
Array
(
[name] => mamals
[id] => 1
)
Array
(
[name] => birds
[id] => 2
)
Array
(
[name] => fishs
[id] => 3
)
Array
(
[name] => reptiles
[id] => 4
)
Code Example:
You can alternatively just access the array names from the froeach such as:
foreach($category as $key =>$categ){
print $categ['name']."\n"; // will list each name starting at the lowest array key.
}
See my test code here.

Add comma Json from php

I have an array inside a foreach to generate data in json, but I should add a comma to validate the code. But I can not ... how can I do it?
$obj = array(
'name' => 'value',
'img' => 'value',
'url' => 'value',
);
echo json_encode($obj);
I have this code
{"name":"value","img":"value","url":"value"}
{"name":"value","img":"value","url":"value"}
{"name":"value","img":"value","url":"value"}
but I would like this code
[
{"name":"value","img":"value","url":"value"},
{"name":"value","img":"value","url":"value"},
{"name":"value","img":"value","url":"value"}
]
Don't echo the JSON in the loop. Put all the objects in another array, and convert that to JSON.
Start with an empty array:
$array = [];
In the loop push onto that array:
$array[] = array(
'name' => 'value',
'img' => 'value',
'url' => 'value',
);
After the loop is done, do:
echo json_encode($array);

How to add items to multidimensional array in php?

I want to build an array of arrays which in the next step will be used as argument to json_encode().
Each element in the array looks like this:
$element = array(
'ITEM_ID' => $itemID,
'STATUS' => $status
)
An example of a desired result with two elements is:
array( array('ITEM_ID' => 1,'STATUS' => "ok"), array('ITEM_ID' => 2,'STATUS' => "not ok") )
I have tried:
array_push($elementArray, $element1);
array_push($elementArray, $element2);
But is does not give the desired result. What should I do?
push_array is not a php functionyou can try with array_push() or more simple
Try with
$element = array(
'ITEM_ID' => $itemID,
'STATUS' => $status
)
$element2 = array(
'ITEM_ID' => $itemID,
'STATUS' => $status
)
$finalArray[] = $element;
$finalArray[] = $element2;
echo "<pre>";
print_r($finalArray);

Alternative to Variable Variables in PHP

In this loop, i am iterating through an array and performing an API call each time. This works fine but I keep reading that using variable variables is not good practice. How could I rewrite this code without using them?
edit: I am not using an array because I have to pass the variables into another template along has other variables outside that array.
template( 'template-name', [ 'graphOne' => $graphOne, 'graphTwo' => $graphTwo, 'outsideVar' => $anothervalue ] );
<?php
// Array of categories for each graph
$catArray = [
'One' => '3791741',
'Two' => '3791748',
'Three' => '3791742',
'Four' => '3791748'
];
foreach ( $catArray as $graphNum => $cat )
{
// Hit API
$graph_results = theme( 'bwatch_graph_call', [
'project' => '153821205',
'category' => $cat
]
);
${"graph{$graphNum}"} = $graph_results;
// Outputs $graphOne, $graphTwo, $graphThree...
}
// Pass vars to template
template( 'template-name', [
'graphOne' => $graphOne,
'graphTwo' => $graphTwo,
'outsideVar' => $anothervalue ]
);
You can use PHP's array_merge when you make your template() call if you have multiple arrays with different key=>value pairs.
http://php.net/array_merge
Here is an example if you have multiple arrays (key=>value pairs) you want to pass to the template.
// Array of categories for each graph
$catArray = [
'One' => '3791741',
'Two' => '3791748',
'Three' => '3791742',
'Four' => '3791748'
];
// Array of category results
$catResult = [];
foreach ( $catArray as $graphNum => $cat )
{
// Hit API
$catResult['graph' . $graphNum] = theme( 'bwatch_graph_call', [
'project' => '153821205',
'category' => $cat
]
);
}
// Now you have an array of results like...
// $catResult['graphOne'] = 'result for One';
// $catResult['graphTwo'] = 'result for Two';
$otherArray1 = ['outsideVar' => $anothervalue];
$otherArray2 = ['somethingElse' => $oneMoreValue];
// Pass all arrays as one
template('template-name', array_merge($catResult, $otherArray1, $otherArray2));

Access multidimensional array without multiple loops

Let's say I have an array formatted like so:
$data = array(
'variables' => array(
'823h9fhs9df38h4f8h' => array(
'name' => 'Foo',
'value' => 'green'
),
'sdfj93248fhfhf88rh' => array(
'name' => 'Bar',
'value' => 'red'
)
)
);
Say I wanted to access the name & values of each array in the variables array. Surely you can access it just looping over the main variables array and not looping over each individual item array? Something like so?
foreach ($data as $k => $v) {
$name = $data['variables'][0]['name'];
}
I'm sure I'm missing something simple...
You can do
foreach ($data['variables'] as $k => $v) {
$name = $v['name'];
}
You can also try this
create a new array containing just the names..
$new_arr = array_column($data['variables'],'name' );
echo $new_arr[0].'<br/>';
echo $new_arr[1].'<br/>';

Categories