I m trying to display no of elements in an array,but its showing 1 when i m trying to print the count
<?php
if(!$xml=simplexml_load_file('sunglasses.xml')){
trigger_error('Error reading XML file',E_USER_ERROR);
}
$array1=array();
foreach($xml as $syn)
{
for($i=0;$i<count($syn->productId);$i++)
{
$array1=$syn->productId;
}
}
echo count($array1, COUNT_RECURSIVE);
?>
There are 10 products in the xml file.So i want the count to be 10,but its printing only 1.
Please tell me whats wrong in the code.
Your formatting of code is horrible.
And yes, there might be 10 elements in the xml, but there is only one in $array1 because only the last assignment is present. You never told to $array1 to push values into the array, despite the fact you declared it as array. Assignation process = does not push values, if explicitly not called via array_push() or [] syntax.
$array1[] = $syn->productId;
Should work.
You should have tested the result at least. var_dump()'ing the $array1 will give you result of only one value - the last value, and you would be able to understand that something is wrong.
Following Change in code will resolved your issue.
<?php
if(!$xml=simplexml_load_file('sunglasses.xml')){
trigger_error('Error reading XML file',E_USER_ERROR);
}
$array1=array();
foreach($xml as $syn)
{
for($i=0;$i<count($syn->productId);$i++)
{
// here need to add the result in array. not to assign value directly to array object.
$array1[] = $syn->productId;
}
}
echo count($array1, COUNT_RECURSIVE);
?>
Related
Any idea on how to restructure the json below:
$jsonArray = [{"Level":"77.2023%","Product":"Milk","Temperature":"4"},
{"Level":"399.2023%","Product":"Coffee","Temperature":"34"},
{"Level":"109.2023%","Product":"Chocolate","Temperature":"14"}]
Expected outcome:
$expected = {"Milk":{"Level":"77.2023%","Temperature":"4"},
"Coffee":{"Level":"399.2023%","Temperature":"34"},
"Chocolate":{"Level":"109.2023%","Temperature":"14"}
}
I'm new and my thinking is get the product value in array and again use foreach loop to find the others value? .
Here's one possibility:
$jsonArray = '[{"Level":"77.2023%","Product":"Milk","Temperature":"4"},
{"Level":"399.2023%","Product":"Coffee","Temperature":"34"},
{"Level":"109.2023%","Product":"Chocolate","Temperature":"14"}]';
$output = array();
foreach (json_decode($jsonArray, true) as $row) {
$product = $row['Product'];
$output[$product] = $row;
unset($output[$product]['Product']);
}
echo json_encode($output);
Output:
{"Milk":{"Level":"77.2023%","Temperature":"4"},
"Coffee":{"Level":"399.2023%","Temperature":"34"},
"Chocolate":{"Level":"109.2023%","Temperature":"14"}
}
Demo on 3v4l.org
This made some trick
$a = '[{"Level":"77.2023%","Product":"Milk","Temperature":"4"},
{"Level":"399.2023%","Product":"Coffee","Temperature":"34"},
{"Level":"109.2023%","Product":"Chocolate","Temperature":"14"}]';
$newAr = array();
foreach(json_decode($a,true) as $key=>$value)
{
$newAr[$value['Product']] = array(
'Level' => $value['Level'],
'Temperature' => $value['Temperature'],
);
}
There are many ways to perform this with Loops in PHP. Other answers demonstrate it accurately. I would also suggest to integrate some form of Error handling, data validation/filtering/restriction in your code to avoid unexpected results down the road.
For instance, json_decode(), either assigned to a variable pre-foreach or straight in the foreach() 1st argument will just raise a warning if the original json is not valid-json, and just skip over the foreach used to construct your final goal. Then if you pass the result (that may have failed) directly to your next logic construct, it could create some iffy-behavior.
Also, on the concept of data-validation & filtering, you could restrict the foreach(), or any other looping mechanism, to check against a Product_List_Array[Milk,Coffee,Chocolate], using if(in_array() ...) so the final/goal object only contains the expected Products, this, in the case the original json has other artifacts. Filtering the values can also increase stability in restricting, for example, Temperature to Float.
i have an array result. i want to print 2 rows(product data) in first page.
next 2 rows in second page and so on. if anybody knows this,please help me to solve it
my array
$data['product_list']
foreach($data['product_list'] as $dat)
{
echo $dat->prd_id;
echo $dat->prd_name;
}
You are doing a foreach loop on an associative array and then trying to access the the contents as objects by using ->. I can only given assumption of what you might be doing. If your array is already populated with a name and id like you have described in your foreach loop this is how you would access the contents in the loop:
foreach($data['product_list'] as $dat)
{
echo $dat['prd_id'];
echo $dat['prd_name'];
}
That is how you would print out the contents providing you had the data stored in your array like so:
$data['product_list'][0] = array('prd_id'=>'id0','prd_name'=>'name0');
$data['product_list'][1] = array('prd_id'=>'id1','prd_name'=>'name1');
$data['product_list'][2] = array('prd_id'=>'id2','prd_name'=>'name2');
Better you try with array_slice();
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,2));
?>
I just started learning PHP and I am having some difficulties with some of the coding.
Hopefully, someone could help me a little.
I'm using this:
if(!empty($_POST['yyy'])) {
foreach($_POST['yyy'] as $a1) {
echo " $a1";}}
The echo will write several results of $a1 depending on how many were selected in the form.
What I want is to save those results to some values so I can add them in MySQL.
Something like this:
if(!empty($_POST['yyy']))
{
foreach($_POST['yyy'] as $a1)
{
echo " $a1"; where $a1 will create a $result1,$result2,$result3(for each isset)
}
}
Then if I use:
echo "$result2";
it will give me the second result.
Not clear whether you are asking about this kind of result or not. But you can use an array to store each values inside the foreach loop.
var data=[];// define an array to access outside of if statement later..
if(!empty($_POST['yyy'])) {
foreach($_POST['yyy'] as $a1){
data[]=$a1;
//or can use array_push() method
array_push(data,$a1);
}
}
/*this will give the second result(because array indexing starts from 0. So to get third result
use data[2])*/
echo data[1];
Furthermore by echoing quoted variable will not give the value of that variable but gives a string literal.
echo "$result2" //output---> $result
$i=0;
foreach($tagss as $tagdetails)
{
if($i==0)
$tags_array[]["00"]=array("id"=>$i,"name"=>"all","type"=>"gift_finder","parent_id"=>null,"url"=>"all","readonly"=>"0","deleted"=>"0");
$tags_array[][$tagdetails->id]=array("id"=>$tagdetails->id,"name"=>$tagdetails->title,"type"=>"gift_finder","parent_id"=>null,"url"=>$tagdetails->title,"readonly"=>"0","deleted"=>"0");
$i++;
}
echo json_encode($tags_array);
my out put of above code is :-
[{"00":{"id":0,"name":"all","type":"gift_finder","parent_id":null,"url":"all","readonly":"0","deleted":"0"}},{"1":{"id":"1","name":"Adventure","type":"gift_finder","parent_id":null,"url":"Adventure","readonly":"0","deleted":"0"}},{"2":{"id":"2","name":"cool","type":"gift_finder","parent_id":null,"url":"cool","readonly":"0","deleted":"0"}}]
that is the right but i want the out put like (just need 0 instead of 00)
so i tried :-
$i=0;
foreach($tagss as $tagdetails)
{
if($i==0)
$tags_array[]["0"]=array("id"=>$i,"name"=>"all","type"=>"gift_finder","parent_id"=>null,"url"=>"all","readonly"=>"0","deleted"=>"0");
$tags_array[][$tagdetails->id]=array("id"=>$tagdetails->id,"name"=>$tagdetails->title,"type"=>"gift_finder","parent_id"=>null,"url"=>$tagdetails->title,"readonly"=>"0","deleted"=>"0");
$i++;
}
echo json_encode($tags_array);
ouput of the above code :-
[[{"id":0,"name":"all","type":"gift_finder","parent_id":null,"url":"all","readonly":"0","deleted":"0"}],{"1":{"id":"1","name":"Adventure","type":"gift_finder","parent_id":null,"url":"Adventure","readonly":"0","deleted":"0"}},{"2":{"id":"2","name":"cool","type":"gift_finder","parent_id":null,"url":"cool","readonly":"0","deleted":"0"}}]
that is logically right that it is put the first element in the array and treat next element at first index but i need 0 index separately
Any suggestion please
thanks in advance .
in summary I need
[{"0":{"id":0,"name":"all","type":"gift_finder","parent_id":null,"url":"all","readonly":"0",
"deleted":"0"}},
{"1":"id":"1","name":"Adventure","type":"gift_finder","parent_id":null,"url":"Adventure","readonly":"0","deleted":"0"}},
{"2":"id":"2","name":"cool","type":"gift_finder","parent_id":null,"url":"cool","readonly":"0","deleted":"0"}
}]
You just need to pass option to your json_encode() call. It is JSON_FORCE_OBJECT:
echo json_encode($tags_array, JSON_FORCE_OBJECT);
then you'll able to result in an object for numeric keys (so you don't need to pass keys from PHP at all). Please, note, that is available since PHP 5.3
I am trying to get the specific value of file extension in this array. All I can do so far is .
I am wanting the fileextention ".jpg"
All I know how to do is echo the values like so using foreach;
file_nameBob7213.jpg file_typeimage/jpeg
file_pathC:/xampp/htdocs/midas/records/
full_pathC:/xampp/htdocs/midas/records/Bob7213.jpg raw_nameBob7213
orig_nameBob72.jpg client_nameafasfafs.jpg **file_ext.jpg** file_size44.96
is_image1 image_width716 image_height474 image_typejpeg
image_size_strwidth="716" height="474"
I am only interested in retrieving the file_ext from this array. How do I select that exact thing?
foreach ($file['upload_data'] as $item => $value)
{
echo $item; echo $value; echo "<br/>";
}
How do I do this? , thanks!
$file['upload_data']['file_ext']
It's just an array within an array, so specify 2 array keys
Incidentally, if you want to see the contents of an array, a quick way of doing it is to use var_export:
var_export($file); # echoes the entire array
You don't need to write a foreach loop every time
$file['upload_data']['file_ext'] contains '.jpg'.