Update: It appears I had snipped out the wrong parts when whittling this down to a short/concise example.
I appears to (incorrectly!!) used if(empty(0)) to detect validation failure when using filter_var_array and FILTER_VALIDATE_INT.
How would be best to do so?
http://codepad.viper-7.com/Z8MLLj
$positiveIntegerFilter = array('filter' => FILTER_VALIDATE_INT,
'options' => array(
'min_range' => 0
)
);
$filter = array(
'apples' => $positiveIntegerFilter,
'oranges' => $positiveIntegerFilter,
'pears' => $positiveIntegerFilter,
'bananas' => $positiveIntegerFilter,
'tangerine' => $positiveIntegerFilter
);
$values = Array(
"apples" => 2,
"oranges" => 4,
"pears" => 0,
"bananas" => -2,
"grapefruit" => 1
);
//Apply filter, and return only what validates
$filteredValues = filter_var_array( $values, $filter );
echo "values: ";
print_r($values);
echo "<br/>";
echo "filteredValues: ";
print_r($filteredValues);
echo "<br/>";
echo "<br/>";
//Examine filtered array for missing parts
foreach($filter as $key => $value) {
echo "key = " . $key . " // value = " . $filteredValues[$key] . "(" . (gettype($filteredValues[$key])) .")". "<br/>" . PHP_EOL;
if(empty($filteredValues[$key])) { //should test if(!isset()) ?
throw new \InvalidArgumentException("Invalid information object on key: `" . $key . "`");
}
}
Related
Here is my code.php:
$info = array (
0 =>
array (
'num' => 1,
'name' => '15 TV',
'stream_type' => 'live',
'stream_id' => 219,
'stream_icon' => 'https://is1-ssl.mzstatic.com/image/thumb/Purple71/v4/5d/2f/1c/5d2f1cb1-3a21-71ff-c10c-e27253ba13dc/source/512x512bb.jpg',
'epg_channel_id' => NULL,
'added' => '1535765481',
'category_id' => '3',
'custom_sid' => '',
'tv_archive' => 0,
'direct_source' => '',
'tv_archive_duration' => 0,
),
479 =>
array (
'num' => 125,
'name' => 'LA DOS',
'stream_type' => 'live',
'stream_id' => 323,
'stream_icon' => 'http://www.dazplayer.com/img_chh/la_dos_espa%C3%B1a.png',
'epg_channel_id' => NULL,
'added' => '1535838540',
'category_id' => '13',
'custom_sid' => '',
'tv_archive' => 0,
'direct_source' => '',
'tv_archive_duration' => 0,
),
);
I have these array and I want to print it, the arrays go to the number 0 from 479. I tried to use the code that it is below but it is not working as well as I want, because it is not printing the right variables. I know that I have to use a loop and the command line for each but I could not be able to do it work.
The variables that I am interested in are:
name
stream_id
stream_icon
category_id
<?php
foreach($info as $x => $x_value) {
echo "Name=" . $x . ", Value=" . $x_value;
echo "<br>;";
}
?>
If someone could help me fixing the bug, i will be thankful.
Regards, Dix
You can try like this way with foreach() loop as $key=>$value pattern. To get values you've to use $value['field_name_for_that_you_need_value']. For example: $x_value['name'] to get the value of name field
<?php
foreach($info as $x => $x_value) {
echo "Name=" . $x_value['name'] . ", Stream Id=" . $x_value['stream_id'].", Stream Icon=".$x_value['stream_icon']. "Category Id=". $x_value['category_id'];
echo "<br>;";
}
?>
DEMO: https://3v4l.org/cvTsc
You could use this method:
print_r($info);
Which will be in your context:
foreach($info as $key => $value)
{
echo "Name=" . $key . ", Value=" . print_r($value, true);
echo "<br>";
}
Documentation
I need to return my collection into an array that Chatfuel, and specifically Messenger, understands. When calling User::get(), I get a collection of all the users, but I need to map it out to the JSON array that Chatfuel expects.
I've previously (when I was using raw PHP and no framework), done it like so:
<?php
$det = array();
while ($row = mysqli_fetch_assoc($results)) {
$row_array['title'] = $row['book-title'] . " | " . $row['edition'] . " Edition";
$row_array['image_url'] = $row['image-url'];
$row_array['subtitle'] = $row['author'];
if (!empty($_SESSION['loggedinuniid'])) {
$urllink = "https://example.com/textbook/?isbn=" . $row['isbn'] . '&uni=' . $_SESSION['loggedinuniid'] . '&submit';
} else {
$urllink = "https://example.com/textbook/?isbn=" . $row['isbn'] . '&submit';
}
$row_array['item_url'] = $urllink;
if ($row['rrs'] == 0) {
$row_array['buttons'] = array(array('type' => 'web_url', 'url' => $urllink, 'title' => 'See Textbook'));
} else {
$row_array['buttons'] = array(array('type' => 'web_url', 'url' => $urllink . '#selling', 'title' => 'Buy Textbook (' . $row['rrs'] . ')'));
}
array_push($det, $row_array);
}
$row_array['title'] = "Find Textbooks on example";
$row_array['subtitle'] = "Search for textbooks sold by your classmates at uni!";
$row_array['image_url'] = "";
$urllink = "https://example.com/";
$row_array['item_url'] = $urllink;
$row_array['buttons'] = array(array('type' => 'web_url', 'url' => $urllink, 'title' => 'See All Textbooks'));
array_push($det, $row_array);
$final = array(
'messages' => array(
array("attachment" => array(
"type" => "template", "payload" => array(
"template_type" => "generic", "elements" => $det,
),
),
),
array("text" => "Hope this helps! You can also always search on example.com!"),
),
);
$post_data = json_encode($final);
exit($post_data);
And, while it got the job done, it isn't really readable or clean.
What's the best way to take an existing collection, and map it out to a custom key/value array I need?
I need a PHP function to output any associative or indexed array.
I have an example of an associative array and a function I have created.
function print_assoc_array(){
$cars = array(
array('Car_brand' => 'Ford', 'Model' => 'Focus', 'Age' => '5 years'),
array('Car_brand' => 'Skoda', 'Model' => 'Octavia', 'Age' => '3 years')
);
foreach ($cars as $key => $value) {
echo $value['Car_brand'] . " " . $value['Model'] . " " . $value['Age'] . "<br/>";
}
}
print_assoc_array();
Any help would be appreciated!
I have below array,
Array
(
[1] => Array
(
[0] => Array
(
[location] => X33
[usernumber] => 1
[order] => XX
[part_number] => Hi
)
[1] => Array
(
[location] => X33
[usernumber] => 1
[order] => YY
[part_number] => 68730
)
)
I want desired output string to echo as below,
'Hello ur oder - XX, YY, part number-Hi, 68730'
How to achieve this output? I was thinking to run a foreach loop, but I'm not sure how I could convert this to a string.
Run a foreachloop and concat
$orderNumber = '';
$partnumber = '';
foreach ($yourArray as $array) {
if ($orderNumber !="") {
$orderNumber.=",";
}
$orderNumber.= $array['order'];
if ($partNumber !="") {
$partNumber.=",";
}
$partNumber.= $array['part_number'];
}
echo "Hello ur order - ".$orderNumber." part number-". $partNumber;
#Frayne Konoks Solution is a nice oneliner:
His Solution with quotes fixed :)
echo 'Hello, ur order - '.implode(", ", array_column($var[1], 'order')).', '.'part number-'.implode(", ", array_column($var[1], 'part_number'))."'";
$var is your array.
Working example:
http://sandbox.onlinephpfunctions.com/code/c95545bdf9d9216d6c80cc06542517e596a0360a
Your must help this code:
<?php
$array = [
[
[
'order' => 1,
'part_number' => 1
],
[
'order' => 2,
'part_number' => 2
]
]
];
$orders = [];
$partnumber = [];
foreach($array as $v) {
foreach($v as $item) {
$orders[] = $item['order'];
$partnumber[] = $item['part_number'];
}
}
$str = sprintf("Hello ur oder - %s, part number-%s", implode(', ', $orders), implode(', ', $partnumber));
echo $str;
Result:
Hello ur oder - 1, 2, part number-1, 2
I changed the array structure a little bit. The code below would be of help:
$arr = array(
array(
'location' => 'X33',
'usernumber' => '1',
'order' => 'XX',
'part_number' => 'Hi',
),
array(
'location' => 'X33',
'usernumber' => '1',
'order' => 'YY',
'part_number' => '68730',
)
);
$order = '';
$p_no = '';
foreach ($arr as $ar) {
$order .= $ar['order'] . ',';
$p_no .= $ar['part_number'] . ',';
}
$order = rtrim($order, ',');
$p_no = rtrim($p_no, ',');
$final_str = 'Hello ur order - ' . $order . ' part number - ' . $p_no;
echo $final_str;
It's as simple as:
foreach($array[1] as $item){
echo "Hello ur order - " . $item["order"] . ", " $item["location"] . ", part number-" . $item["order"] . ", " . $item["part_number"];
}
Im having some problem displaying a multidimensional array...
$copyscape = array (
'query' => 'www.example.html',
'querywords' => 444,
'count' => 230,
'result' => array(
'number' => array(
'index' => 1,
'url' => 'http://www.archives.gov/exhibits/charters/declaration_transcript.html',
'title' => 'Declaration of Independence - Text Transcript',
'minwordsmatched' => 406,
'viewurl' => 'http://view.copyscape.com/compare/w4med9eso0/1'
)
)
);
Basically I want to display everything and also save it in a variable...
echo "<ul>";
foreach($copyscape as $name => $value)
{
echo "<li>" . $name . " : ". $value . "</li>";
}
echo "</ul>";
I tried inserting another set of foreach inside but it gives me an
Invalid argument supplied for foreach()
Try with this code :
$copyscape = array (
'query' => 'www.example.html',
'querywords' => 444,
'count' => 230,
'result' => array(
'number' => array(
'index' => 1,
'url' => 'http://www.archives.gov/exhibits/charters/declaration_transcript.html',
'title' => 'Declaration of Independence - Text Transcript',
'minwordsmatched' => 406,
'viewurl' => 'http://view.copyscape.com/compare/w4med9eso0/1'
)
)
);
function test_print($item, $key)
{
echo "<li>" . $key . " : ". $item . "</li>";
}
echo "<ul>";
array_walk_recursive($copyscape, 'test_print');
echo "</ul>";
use this
foreach ($copyscape as $key=>$value){
echo "<li>" . $key. " : ". $value. "</li>"; // this for main Array
if (is_array ($value))
{
foreach ($value as $childArrayKey => $childArrayValue ){
echo "<li>" . $childArrayKey . " : ". $childArrayValue . "</li>"; // this for childe array
}
}
}
or
foreach ($copyscape as $key=>$value){
echo "<li>" . $key. " : ". $value. "</li>"; // this for main Array
foreach ($value['result']['number'] as $childArrayKey => $childArrayValue ){
echo "<li>" . $childArrayKey . " : ". $childArrayValue . "</li>"; // this for childe array
}
}
In case if you want to have lists inside of lists (nested levels)..
function outputLevel($arr)
{
echo '<ul>';
foreach($arr as $name => $value)
{
echo '<li>';
if (is_array($value))
outputLevel($value);
else
echo $name . ' : ' . $value;
echo '</li>'
}
echo '</ul>';
}
outputLevel($copyscape);
Try following code:
<?php
$copyscape = array (
'query' => 'www.example.html',
'querywords' => 444,
'count' => 230,
'result' => array(
'number' => array(
'index' => 1,
'url' => 'http://www.archives.gov/exhibits/charters/declaration_transcript.html',
'title' => 'Declaration of Independence - Text Transcript',
'minwordsmatched' => 406,
'viewurl' => 'http://view.copyscape.com/compare/w4med9eso0/1'
)
)
);
MultiDimRecuArray($copyscape);
function MultiDimRecuArray($copyscape) {
echo "<ul>";
foreach ($copyscape as $key=>$val) {
if(is_array($val)){
MultiDimRecuArray($val);
}else{
echo "<li>" . $key . " : ". $val . "</li>";
}
}
echo "</ul>";
}
Try something with a recursive function, like this:
function printArray($array)
{
echo "<ul>";
foreach($array as $name=>$value)
{
if(is_array($value))
{
printArray($value);
}
else
{
echo "<li>" . $name . " : ". $value . "</li>";
}
}
echo "</ul>";
}
$copyscape = array (
'query' => 'www.example.html',
'querywords' => 444,
'count' => 230,
'result' => array(
'number' => array(
'index' => 1,
'url' => 'http://www.archives.gov/exhibits/charters/declaration_transcript.html',
'title' => 'Declaration of Independence - Text Transcript',
'minwordsmatched' => 406,
'viewurl' => 'http://view.copyscape.com/compare/w4med9eso0/1'
)
)
);
printArray($copyscape);
Use this
<?php
$copyscape = array (
'query' => 'www.example.html',
'querywords' => 444,
'count' => 230,
'result' => array(
'number' => array(
'index' => 1,
'url' => 'http://www.archives.gov/exhibits/charters/declaration_transcript.html',
'title' => 'Declaration of Independence - Text Transcript',
'minwordsmatched' => 406,
'viewurl' => 'http://view.copyscape.com/compare/w4med9eso0/1'
)
)
);
PrintMultiDimArray($copyscape);
function PrintMultiDimArray($copyscape) {
echo "<ul>";
foreach ($copyscape as $key=>$val) {
if(is_array($val)){
echo "<li>";
PrintMultiDimArray($val);
echo "</li>";
}else{
echo "<li>" . $key . " : ". $val . "</li>";
}
}
echo "</ul>";
}
?>
try this..
echo '<ul>';
displayList($copyscape);
echo '</ul>';
function displayList($arr)
{
foreach($arr as $name => $value) {
if (is_array($value)) {
displayList($value);
}
else {
echo '<li>';
echo $name . ' : ' . $value;
echo '</li>';
}
}
}
Use this:
function print_stuff($arr){
foreach($arr as $key => $val){
if(is_array($val)){
echo "$key: <ul>";
print_stuff($val);
echo "</ul>";
} else {
echo "<li>$key : $val</li>\n";
}
}
}
echo "<ul>";
print_stuff($copyscape);
echo "</ul>";
The code prints a nested list including the key name of the nested lists:
query : www.example.html
querywords : 444
count : 230
result:
number:
index : 1
url : http://www.archives.gov/exhibits/charters/declaration_transcript.html
title : Declaration of Independence - Text Transcript
minwordsmatched : 406
viewurl : http://view.copyscape.com/compare/w4med9eso0/1