I need to fetch value from an array .I need to fetch the value name,value,user_id from an given array
$inner_content='[{"name":"radio","value":"1","id":"1","user_id":"admin#gmail.com","web":"571710720","type":"poll_info","pg":"question_response"},{"name":"fav-color[]","value":"blue"}]'
$id='5'; //value given for expample.
$inner="select * from user_response where POLL_ID=$id";
$inner1=mysql_query($inner);
while($ifet=mysql_fetch_assoc($inner1))
{
$inner_content = $ifet['CONTENT_VALUES'];
$data1 = json_decode($inner_content);
$test1[]=array('name'=>$data1->name);
}
In JSON, square brackets denote an array, and curly braces denote an object. As you can see if you look carefully at $inner_content, it's an array containing a bunch of objects, so you need to index it.
$test1[] = array('name' => $data1[0]->name);
This just gets the name from the first object in the array. If you want to get all the names, you could use a foreach loop on $data1 (but only the first one has all the properties that you say you want).
Related
I have the following JSON:
[
{
"0":"2019-08-31",
"1":"Bank Exp.",
"2":"AED",
"3":"30",
"4":"",
"5":"BANK FEE 10"
},
{
"0":"2019-08-31",
"1":"Inventory",
"2":"AED",
"3":"122",
"4":"",
"5":"DEPOSIT 10000"
},
{
"0":"2019-08-31",
"1":"Petty Cash",
"2":"AED",
"3":"4999",
"4":"",
"5":"DEPOSIT 10000"
}
]
I am trying to Count the number of elements or columns in the Json. The result should be 6.
I have tried with echo count($data_array); (or sizeof) result is 3 (number of rows). How can I count the "columns" in this Json, taking into account that I must set as number of column the Max number of column a specific row has?
Do I have to use a loop to count or can I do it with a single instruction?
Assuming that some var $json contains the JSON code you have above, you should be aware that the following code will result in an array of objects of type stdClass:
$data_array = json_decode($json);
So $data_array is in fact an array, but it contains objects. As you pointed out, this will return the number of rows in your JSON:
echo sizeof($data_array);
Clearly, the number of columns is not the number of rows. If you want to know the number of columns then you'll need to check one or more rows/objects/elements of your $data_array var. It's expedient to just look at the first element:
$col_count = sizeof($data_array[0]);
HOWEVER, this is going to cause an E_WARNING if $data_array's elements are objects of type stdClass:
PHP Warning: sizeof(): Parameter must be an array or an object that implements Countable in /tmp/foo.php on line 33
You could optionally use the second parameter of the json_decode function which will force PHP to decode every curly bracketed object in your JSON code as an associative array instead of stdClass objects:
$data_array = json_decode($json, TRUE);
$col_count = sizeof($data_array[0]);
This yields a $col_count value of6 which is the correct for the first object in your array. You should consider that later elements in $data_array may have either more or fewer columns, depending on the structure of your data. If you are sure that all elements will have the same number of columns, this is adequate, but if you have messy data, you may need to check every element of your data array to see what the true number of columns is:
$data_array = json_decode($json, TRUE);
$col_count = 0;
foreach($data_array as $row) {
$col_count = max($col_count, sizeof($row));
}
var_dump($col_count);
This will yield a $col_count value which reflects the maximum number of columns encountered in any element of your JSON. Clearly, there may be performance considerations if your JSON contains a large number of elements. It all depends on your JSON data and the nature of your application.
EDIT:
Instead of an explicit foreach loop, I think you can get away with this, but it will still require PHP to loop through your data structure. That said, it'll probably be faster:
$max_col_count = max(array_map("count", $data_array));
count($data_array) counts the number of elements in an array. In your case, is 3. But your array is multidimensional (matrix). So you need to count on some index to get the number of columns on that position:
<?php
echo count($data_array[0]);
I have a script that loops through and retrieves some specified values and adds them to a php array. I then have it return the value to this script:
//Returns the php array to loop through
$test_list= $db->DatabaseRequest($testing);
//Loops through the $test_list array and retrieves a row for each value
foreach ($test_list as $id => $test) {
$getList = $db->getTest($test['id']);
$id_export[] = $getList ;
}
print(json_encode($id_export));
This returns a JSON value of:
[[{"id":1,"amount":2,"type":"0"}], [{"id":2,"amount":25,"type":"0"}]]
This is causing problems when I try to parse the data onto my android App. The result needs to be something like this:
[{"id":1,"amount":2,"type":"0"}, {"id":2,"amount":25,"type":"0"}]
I realize that the loop is adding the array into another array. My question is how can I loop through a php array and put or keep all of those values into an array and output them in the JSON format above?
of course I think $getList contains an array you database's columns,
use
$id_export[] = $getList[0]
Maybe can do some checks to verify if your $getList array is effectively 1 size
$db->getTest() seems to be returning an array of a single object, maybe more, which you are then adding to a new array. Try one of the following:
If there will only ever be one row, just get the 0 index (the simplest):
$id_export[] = $db->getTest($test['id'])[0];
Or get the current array item:
$getList = $db->getTest($test['id']);
$id_export[] = current($getList); //optionally reset()
If there may be more than one row, merge them (probably a better and safer idea regardless):
$getList = $db->getTest($test['id']);
$id_export = array_merge((array)$id_export, $getList);
I used cast in order to convert a datatype of one of the columns in my select query.
SELECT cast(user_id as varchar(255)) from cabinet
I need to fetch the result of this value into an array but it returns null value
$listData[] = array(
"member_id" => $row['cast(user_id]
);
How can I display it on array?
SQL:
SELECT cast(user_id AS varchar(255)) AS member_id FROM cabinet
PHP:
$listData = array("member_id" => $row['member_id']);
Basically, you forgot to name the cast function's return in your SQL and used some extremely weird syntax in your PHP. $Array[] = $x; adds element $x as an array item to $Array in PHP. To create a new array, you should run $Array = array();. Some programming languages do indeed force you to put square brackets after a variable's name on value assignation to specify it as an Array/String type, but PHP is not one of them.
To reference an item by key, you have to use the array's name and the key's value in square brackets ($Array[$n], where $n is an integer for arrays with integer indexes, and Array['key'] for arrays with String indexes). 'cast(user_id AS varchar(255))' is not a valid array key, you have to give the SQL function return value a name to be able to reference it as an array item.
Please let me know if this makes sense.
My answer assumes that you are familiar with mySQLi and know how to get $row['member_id'] from the query.
For example, lets say I have an array that looks liked
$stuff = array('random_string_1' => 'random_value_1','random_string_2' => 'random_value_2');
and then I call the asort() function and it changes the array around. How do I get the new first string without knowing what it actually is?
If you want to get the first value of the array you can use reset
reset($stuff);
If you want to also get the key use key
key($stuff);
If you need to get the first value, do it like this:
$stuff = array('random_string_1' => 'random_value_1','random_string_2' => 'random_value_2');
$values = array_values($stuff); // this is a consequential array with values in the order of the original array
var_dump($values[0]); // get first value..
var_dump($values[1]); // get second value..
I'm not 100% but this ($settings) would be called an array in php:
$setting;
$setting['host'] = "localhost";
$setting['name'] = "hello";
but what's the name for this that's different to the above:
$settings = array("localhost", "hello");
Also from the first example how can i remove the element called name?
(please also correct my terminology if I have made a mistake)
I'm not 100% but this ($settings)
would be called an array in php:
You should be 100% sure, they are :)
but what's the name for this that's
different to the above:
This:
$setting['host'] = "localhost";
$setting['name'] = "hello";
And this are different ways of declaring a php array.
$settings = array("localhost", "hello");
In fact this is how later should be to match the first one with keys:
$settings = array("host" => "localhost", "name" => "hello");
Also from the first example how can i
remove the element called name?
You can remove with unset:
unset($setting['name']);
Note that when declaring PHP array, do:
$setting = array();
Rather than:
$setting;
Note also that you can append info to arrays at the end by suffixing them with [], for example to add third element to the array, you could simply do:
$setting[] = 'Third Item';
More Information:
http://php.net/manual/en/language.types.array.php
As sAc said, they are both array. The correct way to declare an array is $settings = array(); (as opposed to just $settings; in your first line.)
The main difference between the first and second way is that the first allows you to use $settings['host'] and $settings['name'], whereas the latter can only be used with numeric indices ($settings[0] and $settings[1]). If you want to use the first way, you can also declare your array like this: $settings = array('host'=>'localhost', 'name'=>'hello');
More reading on PHP arrays
Well this is indeed an array. You have different types of array's in php. The first example you mention is called an Associative Array. Simply an array with a string as a key.
An associative array can be declared in two ways:
1) (the way you declared it):
$sample = array();
$sample["name"] = "test";
2)
$sample = array("name" => "localhost");
Furthermore the first example can also be used to add existing items to an array. For example:
$sample["name"][] = "some_name";
$sample["name"][] = "some_other_name";
When you execute the above code with print_r($sample) you get something like:
Array ( [name] => Array ( [0] => some_name [1] => some_other_name ) )
Which is very usefull when adding multiple strings to an existing array.
Removing a value from an array is very simple,
Like mentioned above, use the unset function.
unset($sample["name"])
to unset the whole name value and values connected to it
Or when you only want to unset a specific item within $sample["name"] :
unset($sample["name"][0]);
or, ofcourse any item you'd like.
So basicly.. the difference between your first example and the latter is that the first is an associative array, and the second is not.
For further reference on arrays, visit the PHP manual on arrays