Get values from Multi-dim Array - php

I do not understand why I can't echo out specific values out of my array..
I grab the $_POST output and save it to an array, filter the array to remove empty keys, display the array, that works all OK, then I try to specify a specific value and I get nothing.
echo "Post OrderArray<pre>";
print_r($_POST[order]);
echo "</pre>";
$order_list = $_POST[order];
$order_list = array_filter(array_map('array_filter', $order_list));
echo "order_list<pre>";
print_r($order_list);
echo "</pre>";
// try to output specific values
echo $order_list[0]['code'] . " _ " . $order_list[0]['qty'] . "<br />";
Post Order Array
Array
(
[0] => Array
(
['qty'] => 3
['code'] => 29468
)
[1] => Array
(
['qty'] =>
)
[2] => Array
(
['qty'] =>
)
[3] => Array
(
['qty'] =>
)
[4] => Array
(
['qty'] =>
)
)
Filtered Order_list Array
Array
(
[0] => Array
(
['qty'] => 3
['code'] => 29468
)
)
_
I think I should be getting "29468 _ 3" but I am not getting any values out of the array.

I copied your sample and added quotes when you are accessing $_POST and am getting the expected output.
If you do not use quotes you will get a notice similar the following depending on your PHP version:
Notice: Use of undefined constant order - assumed 'order' in /private/tmp/post.php on line 13
If you are using PHP 7.1.8 or less the script should still execute without issue. If you are using PHP 7.2 then this behaviour has been deprecated and will not run. You can find more info about this in this related answer.
Working script (in PHP 7.1.8):
// Manually set this for testing...
$_POST = [
'order' => [
['qty' => 3, 'code' => 29468],
['qty' => null],
['qty' => null],
['qty' => null],
['qty' => null],
]
];
echo "Post OrderArray<pre>";
print_r($_POST['order']); // Added quotes
echo "</pre>";
$order_list = $_POST['order']; // Added quotes
$order_list = array_filter(array_map('array_filter', $order_list));
echo "order_list<pre>";
print_r($order_list);
echo "</pre>";
// try to output specific values
echo $order_list[0]['code'] . " _ " . $order_list[0]['qty'] . "<br />";
Output:
php post.php
Post OrderArray<pre>Array
(
[0] => Array
(
[qty] => 3
[code] => 29468
)
[1] => Array
(
[qty] =>
)
[2] => Array
(
[qty] =>
)
[3] => Array
(
[qty] =>
)
[4] => Array
(
[qty] =>
)
)
</pre>order_list<pre>Array
(
[0] => Array
(
[qty] => 3
[code] => 29468
)
)
</pre>29468 _ 3<br />

I found my error, when I was creating the array I used:
$checkboxdata = "<input type=\"checkbox\" name=\"order[$x]['code']\" value=\"$sku\" />$sku";
$qty_checkbox = "<input type=\"text\" name=\"order[$x]['qty']\" class=\"spinner-1\" value=\"\" />";
so my array looked like:
Array
(
[0] => Array
(
['qty'] => 1
['code'] => 29468
Notice the quote marks.
When I edited my code to :
$checkboxdata = "<input type=\"checkbox\" name=\"order[$x][code]\" value=\"$sku\" />$sku";
$qty_checkbox = "<input type=\"text\" name=\"order[$x][qty]\" class=\"spinner-1\" value=\"\" />";
By removing the quotes, I can now access and get my individual values.
I knew it was something silly, and I was right.
Thanks to all for their assistance.
G

Related

Echo out from a multidimensional array

I have this array:
Array
(
[result] => Array
(
[lastModified] => 1465097340000
[name] => Ulminia
[realm] => Zangarmarsh
[battlegroup] => Rampage
[class] => 3
[race] => 4
[gender] => 1
[level] => 100
[achievementPoints] => 14915
[thumbnail] => hellscream/74/113337162-avatar.jpg
[calcClass] => Y
[faction] => 0
[items] => Array
(
[averageItemLevel] => 710
[averageItemLevelEquipped] => 709
[head] => Array
(
[id] => 125899
[name] => Warmongering Gladiator's Helm
[icon] => inv_helm_mail_raidhunter_p_01
[quality] => 4
[itemLevel] => 710
[tooltipParams] => Array
(
[transmogItem] => 71356
[timewalkerLevel] => 100
)
I want to echo out from the [head] array the [id] and the [quality]. If i just echo out the [id] everything works, but if i want to echo out the [quality] too, it doesn´t work.
My code:
$items = $r['result']['items'];
echo 'Head: '.$items['head']['id']['quality']."\n";
foreach($items['head']['tooltipParams'] as $key => $value){
echo 'head_'.$key.': '.$value.'\n';
}
echo $items['head']['id']['quality'];
The above statement means you are printing out the subkey "quality" of key "id", which doesn't exist.
You need to concatenate both key values as follows:
echo $items['head']['id'] . ' ' . $items['head']['quality'];
... or
echo $items['head']['id'], ' ', $items['head']['quality'];
$items['head']['id']['quality']."\n"; is trying to read the element with the key quality inside the array stored inside id. However, id is not an array, which is why this fails.
In order to read two fields, you need to read them seperately:
echo 'Head: ID=' . $items['head']['id'] . ', quality = ' . $items['head']['quality'] . "\n";
Notice that the id and the quality are in the same array.
//ID
echo $items['head']['id'];
//Quality
echo $items['head']['quality'];

How to access sub array in JSON - PHP

I have posted parts of this.. but this a different question for it
i have the below
foreach ($results['comments'] as $item) {
echo 'Date: '. $item['created_at'] .'<br/>';
echo 'Description : '. $item['html_body'] .'<br/>';
echo 'Attachments : '. $item['attacments->url'] .'<br/>';
echo 'Filename : '. $item['file_name'] .'<br/>';
echo "<br>";
}
So basically, my Date and Description work, BUT the attachments wont work, b/c i dont think thats the correct way to get an object thats within an array of an array? hope i explained it correctly.
the comments array has all the date as a single object and so is description, then it has this trailing.
[public] => 1 [trusted] => 1 [attachments] => Array ( [0] => Array ( [url] => https://url/api/v2/attachments/IDHERE.json [id] => ID#[file_name] => name of file here
Take a look at your array dump
[public] => 1
[trusted] => 1
[attachments] => Array (
[0] => Array (
[url] => https://url/api/v2/attachments/IDHERE.json
[id] => ID#
[file_name] => name of file here
Get the values like this:
$Attachments = $item['attachments'];
$AttachmentsUrl = $Attachments[0]['url'];
$Attachmentsid = $Attachments[0]['id'];
$AttachmentsFileName = $Attachments[0]['file_name'];

Illegal string offset in array

I use a library for Synchronize a local WebSQL DB to a server specifically https://github.com/orbitaloop/WebSqlSync.
I use PHP: 5.4.7,
When I try to get the array values ​​as follows, I get the message
Illegal string offset 'clientes'
the $obj var is:
Array
(
[info] =>
[data] => Array
(
[clientes] => Array
(
)
[conceptos_gastos] => Array
(
)
[formaspago] => Array
(
[0] => Array
(
[idFormaPago] => 10
[FormaPago] => qwerqwe
[Dias] => 1
[Cuotas] => 1
[last_sync_date] =>
)
)
[listaprecios] => Array
(
)
[producto] => Array
(
)
[repartidores] => Array
(
)
[tipodocumento] => Array
(
)
[vehiculos] => Array
(
)
[zonas] => Array
(
)
)
)
this is the loop
foreach ($obj as $row => $value) {
echo $row["clientes"]["fomaspago"]["FormaPago"];
}
eternally grateful for any help
it seems to be
$row["data"]["clientes"] // which is an empty array
or
$row["data"]["formaspago"][0]["FormaPago"] // which should output "qwerqwe"
The element $row["clientes"]["fomaspago"]["FormaPago"]; does indeed not exist - look at the output: the 1st row "info" does not have that index, the 2nd row "data" has "clientes" and also "fomasgapo", but does not have a "clientes" "fomasgapo".
You need to either structure your data differently or loop through it differently...
thanks to all but the only way that worked was as follows:
foreach($obj->data->formaspago as $formaspago) {
print " id ".$formaspago->idFormaPago;
print " Formapago ".$formaspago->FormaPago;
print " dias ".$formaspago->Dias;
print " cuotas ".$formaspago->Cuotas;
print " lastsyncdate ".$formaspago->last_sync_date;
}
foreach($obj->data->clientes as $formaspago) {
print " id ".$formaspago->IdCliente;
print " Cliente ".$formaspago->Cliente;
}

Error PHP end of while using PDO Wrapper

Hope can help.
Using php-pdo-wrapper-class I am trying to do 'while' to put results in table.
So far:
$preNic = $db->select('g1_pimps', 'id > 0', 'id, nick, STATUS', '50');
$i=0;
while ($preNic[$i])
{
echo $preNic[$i]['nick'].' - '.$preNic[$i]['id'].'<br />';
$i++;
}
$preNic gives this array
Array
(
[0] => Array
(
[id] => 2
[nick] => PimpNo_2
)
[1] => Array
(
[id] => 3
[nick] => PimpNo_3
)
[2] => Array
(
[id] => 4
[nick] => PimpNo_4
)
etc
)
Now it works but:
a. Is it right way?
b. It gives error notice at end.
Instead of using a while loop use a foreach:
foreach($preNic as $row){
echo $row['nick'].' - '.$row['id'].'<br />';
}
Foreach's are Pimp, Hope it helps

Retrieve name-value pair into PHP array

I need some help. I have a variable containing this string;
[{"id":"17","value":"123456789"},{"id":"18","value":"2012-06-13"},{"id":"19","value":"Kampala"},{"id":"20","value":"1"},{"id":"21","value":"500g"},{"id":"22","value":"Emirrets"},{"id":"23","value":"q"},{"id":"24","value":"q"},{"id":"25","value":"q"},{"id":"26","value":"q"},{"id":"27","value":"q"},{"id":"28","value":"q"},{"id":"29","value":"2"},{"id":"30","value":"987654321"},{"id":"45","value":"1"},{"id":"46","value":"1"}]
I need to retrieve the id and value for each pair and make it any array in PHP.
You can use json_decode and pass the second param as true so it returns an array like this
$json = '[{"id":"17","value":"123456789"},{"id":"18","value":"2012-06-13"},{"id":"19","value":"Kampala"},{"id":"20","value":"1"},{"id":"21","value":"500g"},{"id":"22","value":"Emirrets"},{"id":"23","value":"q"},{"id":"24","value":"q"},{"id":"25","value":"q"},{"id":"26","value":"q"},{"id":"27","value":"q"},{"id":"28","value":"q"},{"id":"29","value":"2"},{"id":"30","value":"987654321"},{"id":"45","value":"1"},{"id":"46","value":"1"}]';
$decoded = json_decode($json,true);
print_r($decoded);
Working Example
Output would be
Array
(
[0] => Array
(
[id] => 17
[value] => 123456789
)
[1] => Array
(
[id] => 18
[value] => 2012-06-13
)
[2] => Array
(
[id] => 19
[value] => Kampala
)
[3] => Array
(
[id] => 20
[value] => 1
)
.......
)
Which you can loop through using foreach like.
foreach($decoded as $de){
// access id with $de['id']
// access value with $de['value']
}
You have got an json string. You can convert it to an array by using function json_decode
Check this code .
$str = '[{"id":"17","value":"123456789"},{"id":"18","value":"2012-06-13"}, {"id":"19","value":"Kampala"},{"id":"20","value":"1"},{"id":"21","value":"500g"},{"id":"22","value":"Emirrets"},{"id":"23","value":"q"},{"id":"24","value":"q"},{"id":"25","value":"q"},{"id":"26","value":"q"},{"id":"27","value":"q"},{"id":"28","value":"q"},{"id":"29","value":"2"},{"id":"30","value":"987654321"},{"id":"45","value":"1"},{"id":"46","value":"1"}]';
$array = json_decode($str);
foreach($array as $temp){
echo "ID : ".$temp->id."\t Value: ".$temp->value;
echo "<br />";
}

Categories