Condition check inside foreach loop - php

I want to filter data where $data['stock'] != 0 from an json array. Can I put the condition check inside the foreach loop? Or, is there any better way to execute the same?
foreach($json['items'] as $data)
{
if(!$data['stock'] == 0) {
echo 'Success';
}
}

There are many ways to achieve what you want to achive. Your code is not wrong. You can also try playing with array_filter().
$json = [
"items" => [[
"name" => "Widget",
"stock" => 3
],[
"name" => "Foo",
"stock" => 0
],[
"name" => "Bar",
"stock" => 2
]]
];
$filtered_array = array_filter($json['items'], function($data){
return $data['stock'];
//Will get rid fo the Foo item because its stock is 0
});
var_dump($filtered_array);
// Will NOT contain the Foo item
Expected output:
array(2) {
[0]=>
array(2) {
["name"]=>
string(6) "Widget"
["stock"]=>
int(3)
}
[2]=>
array(2) {
["name"]=>
string(3) "Bar"
["stock"]=>
int(2)
}
}
This will filter your array to only contain those items that have a value in $data['stock']. You don't need to write != 0, because in PHP, in this particular comparison context, 0 is translated as a boolean false.
Quick demo

Related

PHP foreach in a deeper array

How to foreach through a deeper array in PHP? I want to approach 'price' and list all prices below each other.
$addons = get_product_addons($product->get_id());
When I VAR_DUMP the $addons var, it outputs the below.
array(1) {
[0]=>
array(7) {
["name"]=>
string(8) "Afmeting"
["description"]=>
string(0) ""
["type"]=>
string(6) "select"
["position"]=>
int(0)
["options"]=>
array(10) {
[0]=>
array(5) {
["label"]=>
string(8) "70 x 200"
["price"]=>
string(0) "70.00"
["min"]=>
string(0)""
...
So I want to output this result:
70.00
60.00
Etcetera.. *All prices
I guess that piece of code is what you are looking for:
foreach($addons as $addon)
{
echo $addon["options"]["price"].PHP_EOL;
}
You do not need to use foreach to access nested elements of array. Just use it's key.
PHP_EOL is a constant containing newline for your OS. For web application use special formatting suitable for your page (<br> e.g.)
You can walk or foreach through the items:
<?php
$data =
[
[
'name' => 'orange',
'options' =>
[
'price' => '6.00'
]
],
[
'name' => 'banana',
'options' =>
[
'price' => '4.00'
]
]
];
array_walk($data, function($v) {
echo $v['options']['price'], "\n";
});
Output:
6.00
4.00
Or you could create an array of prices and iterate on that (here using short function syntax):
$prices = array_map(fn($v)=>$v['options']['price'], $data);
var_export($prices);
Output:
array (
0 => '6.00',
1 => '4.00',
)

Invalid argument in foreach loop in php

So this below is the structure of JSON i have when I decode it in PHP, but for some reason I am having hard time to loop through this JSON object. I don't know how can I get each values of "incident","description","technique" from those array to save them In my DB.
array(1) {
["Access"]=>
array(2) {
[0]=>
array(3) {
["incident"]=>
string(19) "sssssssssssssssssss"
["description"]=>
string(10) "ssssssssss"
["technique"]=>
string(19) "Link "
}
[1]=>
array(3) {
["incident"]=>
string(18) "ssssssssssssssssss"
["description"]=>
string(0) ""
["technique"]=>
string(19) "Link "
}
}
}
So far I have this PHP code but it's returning me an error saying invalid argument in first foreach loop.
$objectFirst =($_POST['Access1']);
$data = json_decode($objectFirst,true);
foreach ($data->Access as $tech){
foreach($tech as $incident){
foreach($incident as $ss){
var_dump($ss->incident);
}
}
}
When you access the element with this notation, $data->Access, it means you try to access a property of the $data object. But in your case, $data is an array, therefore you have to use the array notation.
So it should be corrected as $data['Access']. One other issue in your code is the level of loops.
foreach ($data->Access as $tech){
foreach($tech as $incident){
foreach($incident as $ss){
var_dump($ss->incident);
}
}
}
The inner most loop is incorrect because $incident will contain a string, not an array. When you try to access $ss['incident'], it will fail. So just change it to:
foreach ($data['Access'] as $tech){
foreach($tech as $incident){
var_dump($incident);
}
}
Hope it helps!
<?php
$data = [
'access' =>
[
[
'foo' => 'I',
'bar' => 'got'
],
[
'foo' => 'a',
'bar' => 'big'
]
]
];
foreach($data['access'] as $array)
var_dump($array['foo'], $array['bar']);
Output:
string(1) "I"
string(3) "got"
string(1) "a"
string(3) "big"

PHP suppress part of array if duplicate

I have an array of database objects and I'm using foreach() to present the names and projects. Good, now the customer doesn't want duplicate names for when one person has multiple projects. This has to do with variable scope and this is my failed attempt to pull this stunt off. Here's a partial var_dump of the array of objects.
array [
0 => {
["lastName"]=>
string(1) "w"
["projectName"]=>
string(29) "Bone density scanner analysis"
}
1 => {
["lastName"]=>
string(1) "w"
["projectName"]=>
string(29) "analysis of foot"
}
]
What I want to end up with is:
array [
0 => {
["lastName"]=>
string(1) "w"
["projectName"]=>
string(29) "Bone density scanner analysis"
}
1 => {
["lastName"]=>
string(1) ""
["projectName"]=>
string(16) "analysis of foot"
}
]
Here's what I was thinking that doesn't seem to work:
function suppress_name($name){
global $string;
return ($name == $string) ? '' : $string;
}
function overall() {
//$result = database call to get objects
foreach ($result as $item) {
$string = $item->lastName;
$rows = array('Name' => suppress_name($item->lastName), 'project' => $item->projectName);
}
}
Researching I see several references to array_unique() which I use for a flattened array, but I can't see that it would help me here. OK, I thought I could make a function, like the above, to handle duplicates and use the $global but think I'm not grasping how to use globals in this instance. I'm happy to be pointed to a better way, or better search terms. Does this make sense?
Here is a possible approach to your solution, where we store the last names in a one dimensional array then check against it through each iteration of the array. If the lastName is in the array then set the value to ''.
Note the use of the reference (&).
<?php
$arrays = array(
array('lastName' => 'w', 'projectName' => 'Bone density scanner analysis'),
array('lastName' => 'w', 'projectName' => 'analysis of foot')
);
$last_names = array();
foreach($arrays as &$array){
if( in_array($array['lastName'],$last_names) ){
$array['lastName'] = '';
}else{
$last_names[] = $array['lastName'];
}
}
echo '<pre>',print_r($arrays),'</pre>';
It would be easier to work with nested arrays
array [
0 => {
["lastName"]=> string(1) "w"
["projects"]=> array [
0 => {
["projectName"] => string(29) "Bone density scanner analysis"
}
1 => {
["projectName"]=> string(16) "analysis of foot"
}
1 => {
["lastName"] => string(1) "x"
["projects"] => array [
0 => {
["projectName"] => string(16) "analysis of head"
} ]
}
]

Use array_splice() to enter empty values when the array has non-numeric keys [duplicate]

This question already has answers here:
array_splice() for associative arrays
(14 answers)
Closed 7 years ago.
I've taken a look at this question, but I can't seem to get the code to work for my purposes.
I have an array ($array) structured like so, full of data from a database:
array(369) {
array(3) {
["id"] => string(5) "12345",
["title"] => string(11) "Hello World",
["description"] => string(n) "..."
}
array(3) {
["id"] => string(5) "12346",
["title"] => string(13) "Goodbye World",
["description"] => string(n) "..."
}
...
}
However, this array data will be creating a CSV, and I need to insert empty columns as well. Therefore I need the array to end up looking like this:
array(369) {
array(5) {
["id"] => string(5) "12345",
["title"] => string(11) "Hello World",
["title2"] => string(0) "",
["description"] => string(n) "...",
["description2"] => string(0) ""
}
array(5) {
["id"] => string(5) "12346",
["title"] => string(13) "Goodbye World",
["title2"] => string(0) "",
["description"] => string(n) "...",
["description2"] => string(0) ""
}
...
}
I've tried using array_splice() to enter blank values at the relevant points:
array_splice($array, 2, 0, "");
array_splice($array, 4, 0, "");
But this ends up just breaking the array, and later code utlising fputcsv() doesn't even recognise it as an array. How can I enter these blank values?
foreach ($array as $value) {
fputcsv($fp, $value);
}
Please note: What the array key is labelled as does not matter. It can be as suggested above, blank, numeric, zero... all that's important is that I need a blank value.
$array = array_map(function (array $row) {
static $default = [
'id' => null,
'title' => null,
'title2' => null,
'description' => null,
'description2' => null
];
return array_merge($default, $row);
}, $array);
array_merge keeps the structure (keys and order) of the first array, but replaces any values whose keys match with the second array.

getting back a non array

I seem to be having mental issues when it comes to arrays in php. I am not sure why, How ever my array looks like this:
$elementOptions = array(
array(
'type' => 'Text',
'name' => 'test' ,
'isRequired' => true,
'attributes' => array(
'placeholder' => 'content'
),
'subFormName' => 'content'
);
I have a for each loop as such:
foreach ($options as $key => $value) {
if (is_array($value)) {
//do something else
} else {
//do something
}
}
The issue is, if I do a var dump inside the if(isarray()){} I get the following back:
array(1) {
["placeholder"]=>
string(7) "content"
}
array(4) {
["type"]=>
string(4) "Text"
["name"]=>
string(4) "test"
["isRequired"]=>
bool(true)
["attributes"]=>
array(1) {
["placeholder"]=>
string(7) "content"
}
}
now the issue is - I do not want the following in that var dump:
array(1) {
["placeholder"]=>
string(7) "content"
}
I am not sure, based on the "data structure" above, how this 'placeholder' => 'content' is considered an array.....in either case I do not want it as part of the arrays that are var dumped.... it should just be the second array in that var dump coming back.
And that's where you guys come in, why is the place holder coming back as an array when it shouldn't (TMK - to my knowledge).
"placeholder"=>"content" isn't considered an array or coming back as an array, it's a pair in an array that you've called "attributes"
array(4) {
["type"]=>
string(4) "Text"
["name"]=>
string(4) "test"
["isRequired"]=>
bool(true)
["attributes"]=> // this is your array
array(1) { // contents of this array are...
["placeholder"]=> // this is a key
string(7) "content" // this is a variable
} // array ends
}

Categories