Access model without foreach - php

If its possible to access the 'entry_id' data in a foreach loop as below, if I know there is only one item, is there a better way to access it?
$arr = array();
foreach( $order->items as $item ) {
$arr[] = $item->entry_id;
}

If order->items is no-associative array and its only 1 element, you can access it this way:
echo $order->items[0]->entry_id;
But more safe will be check how many items in array:
if(count($order->items) > 0)
echo $order->items[0]->entry_id;

Related

how to Access to nested items in JSON with foreach PHP?

I have the following JSON structure
{"Id":"1","Persons":[{"Name":"Carl","Time":"00:00:03","info":"","Timeext":"","Timeout":"","Timein":""}, {"Name":"Carl","Time":"00:00:03","info":"","Timeext":"","Timeout":"","Timein":""}{"Name":"Luis","Time":"00:00:08","info":"","Timeext":"","Timeout":"","Timein":""}]}
How I can have acces or read the item inside the nest? For example if I just want the value of time for Carl or all information about Carl. Till now I just can get without a problem the single item in the collection 'Id'. The rst nested items not.
I tryed with json_decode like this:
if( $_POST ) {
$arr['Id'] = $_POST['Id'];
$arr['NP'] = $_POST['NP'];
$jsdecode = json_decode($arr);
foreach ($jsdecode as $values){
echo $values->Time;
}
Can PLEASE somebody help me?
if( $_POST ) {
$arr['Id'] = $_POST['Id'];
$arr['NP'] = $_POST['NP'];
$jsdecode = json_decode($arr,true);
foreach ($jsdecode as $values){
echo $values->Time;
}
Adding 'true' to json_decode converts it to array
You are processing it correct , Just add true as the second parameter to json_decode which will be converted to an Array like
$jsdecode = json_decode($arr,true);

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');

Create array of associative arrays [duplicate]

This question already has answers here:
How to store values from foreach loop into an array?
(9 answers)
Closed 8 months ago.
I want to create an array of associative arrays in a while loop. In each iteration of the while loop I want to add a new element in the array. How I can do that? After that I want to pass this array in a foreach and print the data. I have this part of code for now but obviously something is wrong with that.
while($row2 = mysql_fetch_array($result))
{
$myarray = array("id"=>$theid, "name"=>name($id), "text"=>$row2['text']);
}
To add an element in the end of an array use []
Example:
$myarray[] = array("id"=>$theid, "name"=>name($id), "text"=>$row2[text]);
Obviously, okay, first pick it apart so there's something to learn:
while($row2 = mysql_fetch_array($result))
{
...
}
This part look's okay, let's look inside the loop:
$myarray = array("id"=>$theid, "name"=>name($id), "text"=>$row2[text]);
There are multiple points. Probably most important is, as that is inside a loop, you overwrite $myarray in each iteration. You want to add to an array instead. Let's do this:
$myarray = array(); # initialize the array first!
while($row2 = mysql_fetch_array($result))
{
$myarray[] = $row2; # add the row
}
After that you can output it to proof that it basically works:
var_dump($myarray);
That shows you an array that contains all rows. You then only need to change your database query so that it only returns the fields you're interested in.
In case you can't do that with the database, you can manipulate the array as well:
$myarray = array(); # initialize the array first!
while($row2 = mysql_fetch_array($result))
{
$myarray[] = array(
"id" => $theid,
"name" => name($id),
"text" => $row2['text']
);
}
var_dump($myarray);
Now the result should look like you want it. To output $myarray:
foreach ($myarray as $number => $row)
{
echo '<div>Number ', $number, ':<dl>';
foreach ($row as $k => $v)
{
printf("<dt>%s</dt><dd>%s</dd>\n", $k, htmlspecialchars($v));
}
echo '</dl></div>'
}
If you're trying to add to $myarray in each iteration, do it like this:
$myarray[] = array("id"=>$theid, "name"=>name($id), "text"=>$row2[text]);
or like this:
array_push($myarray, array("id"=>$theid, "name"=>name($id), "text"=>$row2[text]));
Obviously your access to $row2 looked wrong, so I assumed that here to be right
$myarray = array();
while($row2 = mysql_fetch_array($result)) {
// append something to your array with square brackets []
$myarray[] = array("id"=> $row2['id'], "name" => $row2['name'], "text"=>$row2['text']);
// or to maker this even shorter you could do
$myarray[] = $row2; // ... because it has the same array key names
}
Then later when you want to read from it:
foreach($myarray as $val) {
echo $val['name'].' (ID: '.$val['id'].') wrote following text: '.$val['text'];
}

Assigning a new Index to an array causes a new array creation?

I was working OpenCart and added such code to Controller to show all the manufacturers to User:
$this->load->model("catalog/manufacturer");
$manufacturers = $this->model_catalog_manufacturer->getManufacturers();
$allbrands = array();
foreach ($manufacturers as $brand)
{
$brand["url"] = $this->url->link("product/manufacturer/product&manufacturer_id=".(string) $brand["manufacturer_id"],"","SSL");
$allbrands[] = $brand;
}
$this->data["manufacturers"] = $allbrands;
It worked just fine but my previous code didn't work which is below:
$this->load->model("catalog/manufacturer");
$manufacturers = $this->model_catalog_manufacturer->getManufacturers();
$allbrands = array();
foreach ($manufacturers as $brand)
{
$brand["url"] = $this->url->link("product/manufacturer/product&manufacturer_id=".(string) $brand["manufacturer_id"],"","SSL");
}
$this->data["manufacturers"] = $manufactures;
What I was thinking is arrays are objects so they are pointed at references so if I change $brand variable then $manufacturers will also have arrays that have "url" as index but didn't work and PHP complains that it doesn't have any "url" index.
Assigning a new index to an array cause it to be recreated with new object in the heap or it extends the current object's place in the heap?
Any ideas, what might it happen?
foreach [docs] is creating copies of the array values:
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.
and
Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset().
This should work:
foreach ($manufacturers as &$brand) {
$brand["url"] = $this->url->link("product/manufacturer/product&manufacturer_id=".(string) $brand["manufacturer_id"],"","SSL");
}
unset($brand);
foreach creates a temporary copy of the objects. Its not a good idea to modify the arrays being referenced in the foreach inside the loop.
You should use pointers to do the modification inside the loop.
Here is an example copied from the docs.
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value); // break the reference with the last element
?>

Output an array

I have created a shortlist feature which acts a bit like a shopping cart. I output the items in the shortlist by:
$i = 0;
while ($i < $countArray){
echo $_SESSION['shortlistArray'][$i]." <a href='shortlistRemoveItem.php?arrayID=$i'>[x]</a><br />";
$i++;
}
and delete an item by
$arrayID = $_GET["arrayID"];
unset($_SESSION['shortlistArray'][$arrayID]);
The problem is that when I delete an item from an array such as $_SESSION['shortlistArray'][2] the output is all messed up as the array is no londer sequential. Should I recode the way my array is outputted or the way I am deleting an item from an array?
The most efficient solution would be simply changing the way your array is outputted:
foreach($countArray as $key => $item){
echo $_SESSION['shortlistArray'][$key]." <a href='shortlistRemoveItem.php?arrayID=$key'>[x]</a><br />";
}
If you insist on changing the way you are deleting an item from the array, consider this alternative:
$arrayID = $_GET["arrayID"];
$tempArray = array();
foreach($countArray as $key => $item){
if($arrayID == $key) continue;
$tempArray[] = $item;
}
$_SESSION['shortlistArray'] = $tempArray;
I' recommend the first option though.

Categories