php function to output indexed and associative arrays - php

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!

Related

Printing Arrays PHP Javascript

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

PHP foreach with multidimensional array not printing all values

I have a very simple multidimensional array and some PHP code. The code should print the p_id values, but it does not do it. Do I really have to add one foreach more or is there other ways?
And here is the array:
Array (
[2764] => Array (
[status] => 0
[0] => Array (
[p_id] => 2895
)
[1] => Array (
[p_id] => 1468
)
)
[5974] => Array (
[status] => 0
[0] => Array (
[p_id] => 145
)
[1] => Array (
[p_id] => 756
)
)
)
Here is my PHP code:
foreach($arr as $innerArray)
foreach($innerArray as $key => $value)
echo $key . "=>" . $value . "<br>";
It prints:
status=>0
0=>Array
1=>Array
status=>0
0=>Array
1=>Array
foreach($arr as $a => $a_value)
{
echo $a . '<br>';
foreach($a_value as $av_arr => $av)
{
if(!is_array($av))
{
echo $av_arr . '=>' . $av . '<br>';
}
else
{
foreach($av as $inner_av => $inner_av_val)
{
echo $inner_av . '=>' . $inner_av_val . '<br>';
}
}
}
}
This simple call to array_walk_recursive() produces the output requested in the question:
array_walk_recursive(
$arr,
function ($value, $key) {
echo $key . "=>" . $value . "<br>";
}
);
But it doesn't make much sense as the output mixes the values of status with the values of p_id.
I would go for a more structured display using the original code with a little more meaning for the names of the variables:
foreach ($arr as $catId => $catInfo) {
// Category ID and details; use other names if I'm wrong
printf("Category: %d (status: %s)\n", $catId, $catInfo['status'] ? 'active' : 'inactive');
foreach ($catInfo as $key => $value) {
if ($key == 'status') {
// Ignore the status; it was already displayed
continue;
}
foreach ($value as $prodInfo) {
printf(" Product ID: %d\n", $prodInfo['p_id']);
}
}
}
The structure of the input array tells me you should first fix the code that generates it. It should group all the products (the values that are now indexed by numeric keys) into a single array. It should look like this:
$input = array(
'2764' => array(
'status' => 0,
'products' => array(
2895 => array(
'p_id' => 2895,
'name' => 'product #1',
// more product details here, if needd
),
1468 => array(
'p_id' => 1468,
'name' => 'product #2',
),
// more products here
),
// more categories here
),
Then the code that prints it will look like this:
foreach ($arr as $catId => $catInfo) {
// Category ID and details; use other names if I'm wrong
printf("Category: %d (status: %s)\n", $catId, $catInfo['status'] ? 'active' : 'inactive');
foreach ($catInfo['products'] as $prodInfo) {
printf(" %s (ID: %d)\n", $prodInfo['name'], $prodInfo['p_id']);
// etc.
}
}
Use a recursive function:
function printIds($arr) {
foreach ($arr as $key => $val) {
if (is_array($val) && array_key_exists("p_id", $val)) {
echo $val["p_id"]."\n";
} elseif(is_array($val)) {
printIds($val);
}
}
}
Working example:
$arr = [
2764 => [
'status' => 0,
['p_id' => 100],
],
4544 => [
'status' => 0,
['p_id' => 100],
],
['p_id' => 100],
];
function printIds($arr) {
foreach ($arr as $key => $val) {
if (is_array($val) && array_key_exists("p_id", $val)) {
echo $val["p_id"]"\n";
} elseif(is_array($val)) {
printIds($val);
}
}
}
printIds($arr);
The function loops all entries of a given array and echo's them out, if they contain an array with a key named "p_id". If it does find a nested array, then it does loop also all child arrays.

Access and join two columns in an array separately

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"];
}

PHP filtering - detecting filter failures

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 . "`");
}
}

How do I get corresponding keys to another key from multidimensional array?

I have a multidimensional array in the following format:
$array = array (
0 =>
array (
'date' => '2013-03-25',
'name' => 'Bob',
'time' => '11'
),
1 =>
array (
'date' => '2013-03-25',
'name' => 'Brian',
'time' => '13'
),
2 =>
array (
'date' => '2013-03-26',
'name' => 'Jack',
'time' => '14'
),
3 =>
array (
'date' => '2013-03-26',
'name' => 'Bob',
'time' => '14'
)
);
I am trying to get the names and corresponding times for each date. I have got the names using the following method:
$array2 = array();
foreach($array as $item) {
$array2[$item['date']][] = $item['name'];
}
and then using:
foreach($array2[$date] as $name)
to run a query on the names returned. But I am not sure how to get the corresponding 'time' key for each 'name' key in the second foreach loop.
Why you don't want to store both name and time for each date key?
$array2 = array();
foreach ($array as $item) {
$array2[$item['date']] []= array($item['time'], $item['name']);
}
You can reach name and time with this code:
foreach ($array2 as $row) {
$name = $row[0];
$time = $row[1];
}
You can try
$list = array();
foreach ( $array as $k => $item ) {
$list[$item['date']][] = array(
$item['name'],
$item['time']
);
}
foreach ( $list as $date => $data ) {
echo $date, PHP_EOL;
foreach ( $data as $var ) {
list($name, $time) = $var;
echo $name, " ", $time, PHP_EOL;
}
echo PHP_EOL;
}
Output
2013-03-25
Bob 11
Brian 13
2013-03-26
Jack 14
Bob 14
try the following:
foreach($array as $item) {
$array2[$item['date'][] = array('name' => $item['name'], 'time' => $item['time']);
}
foreach($array2[$date] as $name) {
echo $name['name'] . ' => ' . $name['time'] . "\n";
}

Categories