I am having a multi-dimensional array. When I access it I get undefined index but I just can't see what I am doing wrong. I very much appreciate if someone has a glue as I am devastating for quite some while now. Thanks!
Dump:
Array
(
[922] => Array
(
[products] => Array
(
[169] => http://www.golf-safari.com/golf_regions/cape_town.asp
)
[company] => stdClass Object
(
[id] => 922
[category_id] => 42
[language_id] => 1
[shipping_from_id] => 0
[name] => Golf-Safari.com
[logo] =>
[company_id] => 922
[area_id] => 414
[country_id] =>
[city_id] => 260
[product_id] => 169
[url] => http://www.golf-safari.com/golf_regions/cape_town.asp
[likes] => 0
[dislikes] => 0
[views] => 0
)
)
)
My access code:
<?php foreach($items as $cmp_id => $company):
$item = $company['company']; // throws undefined index company
$item = $company['products']; // throws undefined index product
?>
<div class="title" title="<?= $item->company ?>">
I am not even getting to the div as error is thrown already on $company['company']
Thanks for all the answers! I don't really know whats wrong. Up to now I always assumed that when there is a dump produced then this dump can be accessed, apparently not. I added my preparation code below.
My preparation code:
foreach($rows as $row)
{
if($row->product_id && !in_array($row->product_id, $products)){
array_push($products, $row->product_id);
}
$products_count[$row->product_id][] = '1';
$ids[$row->id] = $row->id; //store every company id, in order to avoid repetitions count variables
$items[$row->id]['products'][$row->product_id] = $row->url; //cities products
$items[$row->id]['company'] = $row;
}
if($products && is_array($products)){
$query = DB::table('products');
$query->select('id', "name_$this->language AS product");
$query->whereIn('id', $products);
$product_names = $query->get();
}
$sub['items'] = array(
'items' => $items,
'product_names'=> $product_names
);
$item = $company['product']; // throws undefined index product
In here you are passing the wrong key use $item = $company['products'];
print_r($company['products']);
In $company['company'] its an object so you can access the values by the following way
echo $company['company']->name;
the array has about 3 layers. i'll go ahead and assume that the $items is the outtermost layer. according to your structure, your code should look like this:
foreach($item[922] as $cmp_id => $company){
$$cmp_id = $company //converts the index of the item[922] into a variable and assign them the values
$item = $$cmp_id['company'];
$item = $$cmp_id['product'];
}
the first $item will hold this value
[company] => stdClass Object
(
[id] => 922
[category_id] => 42
[language_id] => 1
[shipping_from_id] => 0
[name] => Golf-Safari.com
[logo] =>
[company_id] => 922
[area_id] => 414
[country_id] =>
[city_id] => 260
[product_id] => 169
[url] => http://www.golf-safari.com/golf_regions/cape_town.asp
[likes] => 0
[dislikes] => 0
[views] => 0
)
the second one will hold
(
[169] => http://www.golf-safari.com/golf_regions/cape_town.asp
)
they both contain arrays, i don't think you can use them in the div because none of the new $item arrays has an index [company]. to get the innermost arrays, change the codes to
foreach($items[922][company] as $key => $value){ //or $items[922][products]
$$key = $value;
}
you'll get all the values with their indices as the variable name eg
$category_id =42;
In your example you're overwriting $item each time you declare it. Here is a sample of how to loop through the array - http://phpfiddle.org/lite/code/tr0c-u9vh
foreach($items as $comp_id => $company){
$item = $company['products'];
$company_name = $company['company']['name'];
print_r($item); // because this is still an array
echo $company_name; // this is a specific item
}
You could also use PHP's recursive iterator class - http://php.net/manual/en/class.recursiveiteratoriterator.php
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($items));
foreach($iterator as $key=>$value){
echo $key. "\t" . $value . "\n";
}
In essence by calling it like this you can flatten the array. http://phpfiddle.org/lite/code/5p3h-fb21
foreach(['variable_by_which_get_dump']['922'] as $values)
{
foreach($values as $get_subvalue)
{
foreach($get_subvalue as $get_final_subvalue)
{
echo $get_final_subvalue;
echo '<br>';
}
}
}
Related
I have this Array but i don't know how to get the [discount_amount] based on the [object_ids].
For example i would like to get the 93 value if my [object_ids] contain 81.
Array
(
[0] => Array
(
[id] => rule_5b0d40cd1408a
[membership_plan_id] => 106
[active] => yes
[rule_type] => purchasing_discount
[content_type] => post_type
[content_type_name] => product
[object_ids] => Array
(
[0] => 81
)
[discount_type] => amount
[discount_amount] => 93
[access_type] =>
[access_schedule] => immediate
[access_schedule_exclude_trial] =>
)
[1] => Array
(
[id] => rule_5b0d4e0f3b0b4
[membership_plan_id] => 106
[active] => yes
[rule_type] => purchasing_discount
[content_type] => post_type
[content_type_name] => product
[object_ids] => Array
(
[0] => 110
)
[discount_type] => amount
[discount_amount] => 50
[access_type] =>
[access_schedule] => immediate
[access_schedule_exclude_trial] =>
)
)
You could use a foreach and use in_array to check if the array object_ids contains 81.
foreach ($arrays as $array) {
if (in_array(81, $array["object_ids"])) {
echo $array["discount_amount"];
}
}
Demo
Try with this code .
Assuming $dataArray is the array you have printed.
foreach ($dataArray as $key => $value){
if($value['object_ids'][0] == 83){
$discount_amount = $value['discount_amount'];
}
}
echo $discount_amount
The way I mostly do this is as followed:
# Save retrieved data in array if you want to.
$test = array();
foreach($array as $line){
# Count the row where discount_amount is found.
$test[] = $line['9'];
echo "Result: ".$line['9']. "<br \>\n";
# OR another method is
$test[] = $line['discount_amount'];
echo "Result: ".$line['discount_amount']. "<br \>\n";
}
I need to display a certain object from an array before showing the rest of the array.
The array looks like this:
Array
(
[0] => stdClass Object
(
[template_id] => 91
[template_name] => Alphabet
[template_thumbnail] => blank-template-thumbnail.jpg
[template_create_date] => 1456821665
[template_customer_id] => 0
[template_is_responsive] => no
[template_type] => builder
[template_category] => simple
[sort] => 2
)
[1] => stdClass Object
(
[template_id] => 92
[template_name] => Blank Template
[template_thumbnail] => blank-template-thumbnail.jpg
[template_create_date] => 1456821670
[template_customer_id] => 0
[template_is_responsive] => no
[template_type] => builder
[template_category] => simple
[sort] => 2
)
[2] => stdClass Object
(
[template_id] => 31
[template_name] => Holiday Specials
[template_thumbnail] => accommodation-1-20110926.jpg
[template_create_date] => 1456821660
[template_customer_id] => 0
[template_is_responsive] => no
[template_type] => builder
[template_category] => Accommodation
[sort] => 3
)
)
I need to show Blank Template first and then show the rest alphabetically (the order it is in now.
Is there a more elegant solution than looping through the array twice? The size of the array can be anything from 1 (the blank template) to countless objects.
$str="";
for($i=0;$i<=count($arr);$i++){
if($arr[$i]['template_name'] == "Blank Template"){
echo $arr[$i]['template_name'];
}else{
$str .= $arr[$i]['template_name']. "<br>";
}
}
echo $str;
Try this:
$firstItem = null;
$outArray = [];
foreach($yourArray as $item){
if($item->template_name == 'Blank Template'){
$firstItem = $item;
}else{
$outArray[$item->template_name] = $item;
}
}
ksort($outArray,SORT_STRING);
array_unshift($outArray,$firstItem);
Just one loop. Pay attention that this way of doing things, just work if you have uniqueness on the template_name!
Hope it helps.
This will work for you, try
<?php
$dataArray = array(0=>array('template_id'=>91,'template_name'=>'Alphabet'),
1=>array('template_id'=>92,'template_name'=>'Blank Template'),
2=>array('template_id'=>31,'template_name'=>'Holiday Specials')
);
$newArray = array();
foreach($dataArray as $key => $val)
{
if(in_array('Blank Template',$val))///find the key for black template
{
unset($dataArray[$key]); ///unset black temp from original array
$newArray[] = $val;///push black temp into new array at 0 index
foreach($dataArray as $k => $v)
{
$newArray[] = $v; ///push the renaming values into new array
}
}
}
echo "<pre>"; print_r($newArray);
?>
This will give you :
Array
(
[0] => Array
(
[template_id] => 92
[template_name] => Blank Template
)
[1] => Array
(
[template_id] => 91
[template_name] => Alphabet
)
[2] => Array
(
[template_id] => 31
[template_name] => Holiday Specials
)
)
LIVE EXAMPLE : CLICK HERE
I am needing to echo out the [number], but as you can see each array has a different parent [], how do I by pass the first one and get go to the [number]?
I basically need to skip over first [], and go to the second on that is [number]
Array
(
[e2a4789d22ff47779722b8d8643894cd] => Array
(
[type] => workphone
[visibility] => public
[number] => 999-999-9999
[id] => 2
[order] => 0
[preferred] => 1
)
)
Array
(
[1603ebeff250437480f5ce046cac36aa] => Array
(
[type] => workphone
[visibility] => public
[number] => 999-999-9999
[id] => 3
[order] => 0
[preferred] => 1
)
)
Array
(
[215590630122] => Array
(
[type] => workphone
[visibility] => public
[number] => 999-999-9999
[order] => 0
[preferred] =>
)
)
Your solution for this is using the foreach-loop. Which gives you then the value of the element as variable you tell PHP to assign to.
foreach($array as $element) {
}
You have to use reset function to get the first element of array.
e.g.
$firstElement = reset($arr);
echo $firstElement['number'];
You can just loop over the elements in the array(s) using foreach.
foreach($data as $ele){
foreach($ele as $id=>$val){
echo $val['number'];
}
}
Just an example
$array = $yourarray;
foreach($array as $k=>$v) {
echo $v['number'] . '<br>';
}
hope this helps...
The first bracket is just a unique key index foreach subsequent set of data. for example you can get the first set by accessing through the key like this
$data['e2a4789d22ff47779722b8d8643894cd']
// will return
Array
(
[type] => workphone
[visibility] => public
[number] => 999-999-9999
[id] => 2
[order] => 0
[preferred] => 1
)
loop through the array to access the data you want,
// declare your array if you want to save data in array
$numbers = [];
foreach($data $key =>$value){
// echo just the number
echo $value['number'];
// echo the key and number
echo $key.' '.$value;
// or you can build an array
$numbers[$key] = $value['number'];
}
print_r($numbers);
Hope you find this useful, for more info about arrays take a look at this http://php.net/manual/en/language.types.array.php
foreach ($array as $id => $element)
{
// will echo 999-999-9999
echo $element['number'];
}
$array is the whole data structure. We go through as index, that is the $id, which is for example e2a4789d22ff47779722b8d8643894cd and the $element is the element in the $array[$id] so in the $array[e2a4789d22ff47779722b8d8643894cd]
So the $element is the small array in the large array, and it contains data like:
Array
(
[type] => workphone
[visibility] => public
[number] => 999-999-9999
[id] => 2
[order] => 0
[preferred] => 1
)
So if you need the number attribute, you type $element['number'] and you get it.
If your variable was in an array called $elements then it would look like:
$elements['e2a4789d22ff47779722b8d8643894cd']['number']
I have Array and i need to get summ of quantity * price. But the array keys on the third level is different.
I use this PHP code but i only can take price & quantity for first item ['506-p1-8_p2-_p3-']
$quantity = $elements['1af7e792-bcff-4a6c-9bdb-dd5023b0251a']['items']['506-p1-8_p2-_p3-'][quantity];
$price = $elements['1af7e792-bcff-4a6c-9bdb-dd5023b0251a']['items']['506-p1-8_p2-_p3-'][price];
$summ = $price*$quantity;
How to parse all levels to get Summ = (price * quantity)
Thank to all who can help me
Array
(
[1af7e792-bcff-4a6c-9bdb-dd5023b0251a] => Array
(
[is_advance] => 1
[items] => Array
(
[506-p1-8_p2-_p3-] => Array
(
[hash] => 506-p1-8_p2-_p3-
[sku] => 501
[itemId] => 506
[quantity] => 6
[price] => 80.75
[currency] => UAH
[priceDesc] =>
[priceParams] => Array
(
[u0420u0430u0437u043cu0435u0440] => 8
)
[name] => qwerty
)
[498-p1-6_p2-_p3-] => Array
(
[hash] => 498-p1-6_p2-_p3-
[sku] => 498
[itemId] => 498
[quantity] => 5
[price] => 500
[currency] => UAH
[priceDesc] =>
[priceParams] => Array
(
[u0420u0430u0437u043cu0435u0440] => 6
)
[name] => qwerty
)
)
)
)
It's hard to tell how the array is generated in the first place. So just going off of the code you've posted, this should sum up the total for every item contained in the array.
$items = $elements['1af7e792-bcff-4a6c-9bdb-dd5023b0251a']['items'];
$sum = 0;
foreach($items as $item) {
$sum += $item['quantity'] * $item['price'];
}
In the sense of flexibility, you want your code as portable as possible. I assume your id isn't always going to be 1af7e792-bcff-4a6c-9bdb-dd5023b0251a, so you'll want to loop through the data that is returned.I don't know how you get the data, that's up to you.
So something like this, should gather the data you require and create an array:
$d = array();
foreach ($data as $id => $item) {
foreach ($item as $key => $values) {
$d[$id][$key]['sum'] = $values['price'] * $values['quantity'];
}
}
print_r($d);
Note: The above code is untested
So My problem is:
I want to create nested array from string as reference.
My String is "res[0]['links'][0]"
So I want to create array $res['0']['links']['0']
I tried:
$result = "res[0]['links'][0]";
$$result = array("id"=>'1',"class"=>'3');
$result = "res[0]['links'][1]";
$$result = array("id"=>'3',"class"=>'9');
when print_r($res)
I see:
<b>Notice</b>: Undefined variable: res in <b>/home/fanbase/domains/fanbase.sportbase.pl/public_html/index.php</b> on line <b>45</b>
I need to see:
Array
(
[0] => Array
(
[links] => Array
(
[0] => Array
(
[id] => 1
[class] => 3
)
)
)
[1] => Array
(
[links] => Array
(
[0] => Array
(
[id] => 3
[class] => 9
)
)
)
)
Thanks for any help.
So you have a description of an array structure, and something to fill it with. That's doable with something like:
function array_create(&$target, $desc, $fill) {
preg_match_all("/[^\[\]']+/", $desc, $uu);
// unoptimized, always uses strings
foreach ($uu[0] as $sub) {
if (! isset($target[$sub])) {
$target[$sub] = array();
}
$target = & $target[$sub];
}
$target = $fill;
}
array_create( $res, "[0]['links'][0]", array("id"=>'1',"class"=>'3') );
array_create( $res, "[0]['links'][1]", array("id"=>'3',"class"=>'9') );
Note how the array name itself is not part of the structure descriptor. But you could theoretically keep it. Instead call the array_create() function with a $tmp variable, and afterwards extract() it to achieve the desired effect:
array_create($tmp, "res[0][links][0]", array(1,2,3,4,5));
extract($tmp);
Another lazy solution would be to use str_parse after a loop combining the array description with the data array as URL-encoded string.
I have a very stupid way for this, you can try this :-)
Suppose your string is "res[0]['links'][0]" first append $ in this and then put in eval command and it will really rock you. Follow the following example
$tmp = '$'.'res[0]['links'][0]'.'= array()';
eval($tmp);
Now you can use your array $res
100% work around and :-)
`
$res = array();
$res[0]['links'][0] = array("id"=>'1',"class"=>'3');
$res[0]['links'][0] = array("id"=>'3',"class"=>'9');
print_r($res);
but read the comments first and learn about arrays first.
In addition to mario's answer, I used another function from php.net comments, together, to make input array (output from jquery form serializeArray) like this:
[2] => Array
(
[name] => apple[color]
[value] => red
)
[3] => Array
(
[name] => appleSeeds[27][genome]
[value] => 201
)
[4] => Array
(
[name] => appleSeeds[27][age]
[value] => 2 weeks
)
[5] => Array
(
[name] => apple[age]
[value] => 3 weeks
)
[6] => Array
(
[name] => appleSeeds[29][genome]
[value] => 103
)
[7] => Array
(
[name] => appleSeeds[29][age]
[value] => 2.2 weeks
)
into
Array
(
[apple] => Array
(
[color] => red
[age] => 3 weeks
)
[appleSeeds] => Array
(
[27] => Array
(
[genome] => 201
[age] => 2 weeks
)
[29] => Array
(
[genome] => 103
[age] => 2.2 weeks
)
)
)
This allowed to maintain numeric keys, without incremental appending of array_merge. So, I used sequence like this:
function MergeArrays($Arr1, $Arr2) {
foreach($Arr2 as $key => $Value) {
if(array_key_exists($key, $Arr1) && is_array($Value)) {
$Arr1[$key] = MergeArrays($Arr1[$key], $Arr2[$key]);
}
else { $Arr1[$key] = $Value; }
}
return $Arr1;
}
function array_create(&$target, $desc, $fill) {
preg_match_all("/[^\[\]']+/", $desc, $uu);
foreach ($uu[0] as $sub) {
if (! isset($target[$sub])) {
$target[$sub] = array();
}
$target = & $target[$sub];
}
$target = $fill;
}
$input = $_POST['formData'];
$result = array();
foreach ($input as $k => $v) {
$sub = array();
array_create($sub, $v['name'], $v['value']);
$result = MergeArrays($result, $sub);
}