Display a condition from an array - php

Need help guys, below is a var_dump array, I am very noob in php and I am very confused on how to do this, basically all I need is a condition
$fittin_colour_image = get_field('featured_images', get_the_ID());
Above is a code using ACF
var_dump($fittin_colour_image);
below is the result
array (size=2)
0 =>
array (size=3)
'fitting_colour' =>
array (size=1)
0 => string 'Black' (length=5)
'image' => string 'http://localhost/mysite.com/wp-content/uploads/2018/04/image-black.jpg' (length=101)
'image_description' => string '' (length=0)
1 =>
array (size=3)
'fitting_colour' =>
array (size=1)
0 => string 'White' (length=5)
'image' => string 'http://localhost/mysite.com/wp-content/uploads/2018/05/image-white.png' (length=100)
'image_description' => string '' (length=0)
I want to have a condition like this
if this array has a color "Black" then display its image
I am currently using this code
if ($fittin_colour_image[0]['fitting_colour'][0] == 'Black') {
echo $fittin_colour_image[0]['image'];
}
its a bit of a hassle since every time I change the condition I change the [0], sorry but I am confused now, don't know what to say, please help

You're very close. Instead of hard-coding the index (0 in your case) you can, instead, loop over the array and display the image:
foreach ($fittin_colour_image as $image) {
if ($image['fitting_colour'][0] == 'Black') {
echo $image['image'];
}
}

test this
$fittin_colour_image = get_field('featured_images', get_the_ID());
if(!empty($fittin_colour_image)){ // Test if array not empty
foreach ($fittin_colour_image as $image) {
if(!empty($image['fitting_colour'][0]) && $image['fitting_colour'][0] === 'Black'){
echo '<img src="'.$image['image'].'" alt="'.$image['image_description'].'" />';
}
}
}

Related

PHP. How to get the position of an element inside an unidimensional and multidimensional array? [duplicate]

This question already has answers here:
php - get numeric index of associative array
(7 answers)
Closed 3 years ago.
For instance, in the following code, how to get the position -order- of a given element inside the array:
<?php
$cars=array("Volvo","BMW","Toyota","Tesla","Volkswagen");
//for Volvo, an echo statement should return 1
//for BMW, an echo statement should return 2
//for Toyota, an echo statement should return 3 ... and so on ...
?>
Update: After receiving some useful contributions regarding the implementation of search_array(), I was wondering if I can apply the same for arrays contained inside another array. vardump() for a multidimensional array shows me the following:
array (size=3)
'home' =>
array (size=6)
'label' =>
object(Magento\Framework\Phrase)[5814]
private 'text' => string 'Home' (length=4)
private 'arguments' =>
array (size=0)
...
'title' =>
object(Magento\Framework\Phrase)[5815]
private 'text' => string 'Go to Home Page' (length=15)
private 'arguments' =>
array (size=0)
...
'link' => string 'http://example.com/example.html' (length=23)
'first' => boolean true
'last' => null
'readonly' => null
'category4' =>
array (size=6)
'label' => string 'Transport' (length=9)
'link' => string 'http://example.com/example.html' (length=23)
'title' => null
'first' => null
'last' => null
'readonly' => null
'category686' =>
array (size=6)
'label' => string 'Transport' (length=15)
'link' => string '' (length=0)
'title' => null
'first' => null
'last' => boolean true
'readonly' => null
How to get in this case the position of category4 in regard to the array of size=3?
array_search() will let you find the position of an element or it returns FALSE if the element was not found. Read more about it at http://php.net/manual/en/function.array-search.php
From the documentation, this is what can be returned from this function:
Return Values
Returns the key for needle if it is found in the array, FALSE otherwise.
And here is an example:
<?php
$cars=array("Volvo","BMW","Toyota","Tesla","Volkswagen");
//for Volvo, an echo statement should return 1
//for BMW, an echo statement should return 2
//for Toyota, an echo statement should return 3 ... and so on ...
$volvoPosition = array_search("Volvo", $cars);
if ($volvoPosition !== false) {
// Volvo position was found at index/position 0 of the array.
print $volvoPosition; // This gives the value 0
} else {
// "Volvo" was never found in the array.
}
?>
As the example is very simple, meaning, is just an array of strings, then you may use array_flip, which is going to return an array that flips the keys with the values, so we can do:
$cars = ["Volvo","BMW","Toyota","Tesla","Volkswagen"];
$flipped = array_flip($cars);
//for Volvo, => int(0)
var_dump($flipped['Volvo']);
//for BMW, => int(1)
var_dump($flipped['BMW']);
Also remember that the array start with 0 and not with 1, then the index of "Volvo" is 0 and not 1.
Yes you can use array_search(), but array_search() returns the index of the element which is start from 0, so you can do like below,
this is your array
$cars=array("Volvo","BMW","Toyota","Tesla","Volkswagen");
echo (array_search("Volvo",$cars)) + 1; //you can getting 1 as output

PHP: Remove empty values from array and shift values up

I'm trying to create a function that shifts array values up a key if the previous key is empty and one after is set. E.g. this array:
array (size=4)
'row1' => string 'row1' (length=4)
'row2' => string '' (length=0)
'row3' => string '' (length=0)
'row4' => string 'row4' (length=4)
should become this after my function call:
array (size=4)
'row1' => string 'row1' (length=4)
'row2' => string 'row4' (length=4)
'row3' => string '' (length=0)
'row4' => string '' (length=0)
I do have a working function, however, it uses a lot of if statements and I'm 100% sure that it could be done more efficiently, any ideas on how to achieve efficiently?
Thanks
You can do this in a single line, making use of array_ functions.
$o = array_combine(array_keys($input), array_pad(array_filter($input), count($input), ''));
array_filter will, by default, remove any empty values from the array
array_pad will pad the array to the length of the original array, adding an empty string
array_keys will get the keys of the original array
array_combine will combine the keys with the values
The above would output the following:
array (size=4)
'row1' => string 'row1' (length=4)
'row2' => string 'row4' (length=4)
'row3' => string '' (length=0)
'row4' => string '' (length=0)
Here's a demo
Lets try this with a big array, and hope this will help you out. The way of question is different but your question is same as
1. Getting empty values at end.
2. Non empty at starting without changing order
3. Without changing keys order
If you think about any array this result come to end.
Try this code snippet here
<?php
$array=$tempArray=array(
'row1' => 'row1',
'row2' => '' ,
'row3' => '',
'row6' => 'row6' ,
'row4' => 'row4' ,
'row5' => '',
'row7' => 'row7' ,
'row8' => ''
);
$result=array();
$tempArray= array_values($tempArray);
$tempArray=array_values(array_filter($tempArray));
foreach(array_keys($array) as $key_key => $key)
{
if(!empty($tempArray[$key_key]))
{
$result[$key]=$tempArray[$key_key];
}
else
{
$result[$key]="";
}
}
print_r($result);
Output:
Array
(
[row1] => row1
[row2] => row6
[row3] => row4
[row6] => row7
[row4] =>
[row5] =>
[row7] =>
[row8] =>
)
unfortunately you did not share your code, so we cannot know what you do exactly
also it would be helpful if you added the array as code we can run directly and do not need to edit/re-create
I would
ignore the keys for processing the list when possible
unset entries that are nor needed any longer
iterate lists with foreach
apart from this you can sort lists in PHP (by value, key; asc, desc; with/without association), they have a nice overview on that in the manual.
example steps:
<?php
$a['row1'] = 'row1';
$a['row2'] = '';
$a['row3'] = '';
$a['row4'] = 'row4';
print_r( $a );
arsort($a);
print_r( $a );
//get rid of double entries
$f=array_flip( $a );
//get rid of empty entries
unset($f['']);
print_r( array_flip( $f ) );
?>
EDIT
$yourarr=array('row1'=>"row1",'row2'=>"",'row3'=>"",'row4'=>"row4");
$array1=array();
$array2=array();
foreach ($yourarr as $key =>$val){
if(empty($val)){
$array2[$key]=$val;
}else{
$array1[$key]=$val;
}
}
$newarr=array_merge($array1,$array2);
//<!-- Try This if you want to remove the empty indexes just put ! infront of the empty and delete the else part and to reset the row count -->
$i=1;
$newarr2=array();
foreach($newarr as $key =>$val){
$newarr2['row'.$i]=$val;
$i++;
}
var_dump($newarr2);
OUTUT
D:\wamp64\www\test\index.php:21:
array (size=4)
'row1' => string 'row1' (length=4)
'row2' => string 'row4' (length=4)
'row3' => string '' (length=0)
'row4' => string '' (length=0)

SQL/PHP sort fields from a form to make insert

I've got a form which users can add new rows by clicking on a button and automatically, it adds +1 on the field's name.
So for example, I've got my train_id_1, train_type_1 and my user wants to add a new one, so now I've got train_id_2 and train_type_2.
In order to save this in my database, I would like to sort and seperate train_type_1 / train_type_2... to make a foreach and then to save in my database.
So, the var_dump of my $_POST looks like :
array (size=60)
'train_id_1' => string ' 07:36' (length=6)
'train_type_1' => string ' -Z' (length=3)
'user_id_1' => string 'CPN' (length=3)
'event_criter_1' =>
array (size=3)
0 => string 'test' (length=4)
1 => string '234' (length=3)
2 => string '532' (length=3)
'train_id_2' => string ' 08:32' (length=6)
'train_type_2' => string ' -X' (length=3)
'user_id_2' => string 'CPN' (length=3)
'event_criter_2' =>
array (size=3)
0 => string 'TESTG' (length=5)
1 => string 'GGG' (length=3)
2 => string 'AETG' (length=4)
'train_id_3' => string ' 08:36' (length=6)
'train_type_3' => string ' -Z' (length=3)
'user_id_3' => string 'CPN' (length=3)
'event_criter_3' =>
array (size=1)
0 => string '' (length=0)
'train_id_4' => string ' 09:04' (length=6)
'train_type_4' => string ' -X' (length=3)
'user_id_4' => string 'CPN' (length=3)
'event_criter_4' =>
array (size=1)
0 => string '' (length=0)
Do you know how I can make abcd_1 separate from abcd_2 to make my foreach (or another solution) ?
Thank you!
Loop through your array, matching _1 and insert the posted elements as one row. Then increment and match _2 etc..
$postedElements = $_POST;
$elementsPerRow = 4;
$numRows = count($postedElements)/$elementsPerRow;
// loop through the number of 'rows' to insert
for($i=1;$i<=$numRows;$i++){
// Build an array to store matched elements to insert
$elementsToInsert = array();
//process the complete _POST array each time...
foreach($postedElements as $name => $value){
// ...get the 'row' (the bit after the underscore)...
//list($value,$row) = explode('_',$name); // doesn't work for 2 underscores..
$row = end(explode($name)); // This will
if($row == $i){
// ...and add elements that match to an insert array
// $elementsToInsert[] = $name;
$elementsToInsert[$name] = $value;
}
}
// insert $elementsToInsert into DB
}
I think, at first You need to have a amount of records in array through count($arr). Then use usual for loop:
//output of field names
for ($i = 0; $i < count($arr); $i++){
//Work with array
}
Make a new array.
Then add a data from loop into new array.
I think it could help You.
And by which reason You need to sort them?

PHP: Get array values based on conditions

I've been puzzling a lot with getting the correct values based on some conditions. First, let's look at what PHP's function var_dump() returned. This is just the important part in adjustment to the data I look for. Check the whole json object here.
array (size=3)
0 =>
array (size=12)
'inputs' =>
array (size=2)
0 =>
array (size=3)
'prev_out' =>
array (size=7)
'addr' => string '1AvY95SQqtWy6MKWZbE3Xnqant9F3whfPH' (length=34)
'value' => int 1583375
1 =>
array (size=3)
'prev_out' =>
array (size=7)
'addr' => string '1KEUVc2TxDh1VAcvrS5p3PtJHcRwzrvin1' (length=34)
'value' => int 150000
'out' =>
array (size=2)
0 =>
array (size=7)
'addr' => string '1Djp9h8mR3qqRz6v54nx265b8jZuqYNQ8j' (length=34)
'value' => int 1046166
1 =>
array (size=7)
'addr' => string '13W7N4NFwpTkYnHuVABcQfdrvDyszDqwkr' (length=34)
'value' => int 677209
What you just saw was the output of $data['txs']. The outer array is a list of transactions. Within each, the details are specified. The length of the "inputs" and "out" can change! I want to get the value of each transaction ($data['txs'][index of transaction]['out']['value']) that meets the following criteria:
The value of the "out" transaction should be bigger than zero.
The address of the "out" transaction should be equal to $address.
$address is not in the "inputs" transaction. E.g: $address can not be in the array of all ['inputs'][count(inputs)]['inputs']['prev_out']['addr'].
Here is my last attempt at solving this. The problem is that $result stays empty, even though the address 13W7N4NFwpTkYnHuVABcQfdrvDyszDqwkr is there and the result should be 677209.
$i = 0;
$txresult = array();
foreach($data['txs'] as $ct => $cv) {
$index = count($data['txs'][$i]['inputs']) - 1;
$addressindex = array();
for($testindex = 0; $testindex < $index; $testindex++) {
$addressindex[] = $data['txs'][$i]['inputs'][$index]['prev_out']['addr'];
}
$counter = count($data['txs'][$i]['out']) - 1;
for($count = 0; $count < $counter; $count++) {
if ($data['txs'][$i]['out'][$count]['value'] > 0 && $data['txs'][$i]['out'][$count]['addr'] == $address && !in_array($address, $addressindex)) {
$result = $data['txs'][$i]['out'][$count]['value'];
}
}
$i++;
}
Remember I cut the scope of the code, so it's possible some suggestions that require too much change may not work. I will do my best to respond to your questions asap.
Figured it out on my own terms. #Wrikken was instrumental to come to a conclusion.
The solution was pretty easy. Only two things:
$i++ shouldn't be in any of the for-loops, so I put it at the end of the foreach loop.
I had to unset $addressindex, $counter and $index.

PHP: IF sentence is run, but dumps says it shouldn't

im sitting with a pretty simple image uploader, where the first image uploaded is going to be treated in a special manner. I then run a loop over all the files, and skip the first image.
For this i have named the first image headImage, and i skip it when it has been moved, and done the other stuff to it.
I have cut out all excess code, and are only displaying the loop causing my problem:
Sorted image array:
array (size=5)
'headImage' =>
array (size=5)
'name' => string '8-skilling-1606-eller-07-54-1-h93a.jpg' (length=38)
'type' => string 'image/jpeg' (length=10)
'tmp_name' => string '/tmp/phpNUoAtX' (length=14)
'error' => int 0
'size' => int 37748
0 =>
array (size=5)
'name' => string '807003718_2_Big.jpg' (length=19)
'type' => string 'image/jpeg' (length=10)
'tmp_name' => string '/tmp/php1TXBdm' (length=14)
'error' => int 0
'size' => int 36328
Foreach loop which skips if the fileKey is "headImage", and dumps the fileKey
foreach($uploadFiles as $fileKey => $file){
if($fileKey == "headImage"){
var_dump($fileKey);
continue;
}
}
And the output from var_dump:
string 'headImage' (length=9)
int 0
Now, why is the if sentence ran when the value of $fileKey clearly isn't "headImage"?
Because "string" == 0 in PHP.
You have to compare using type too, try === comparison:
foreach($uploadFiles as $fileKey => $file){
if($fileKey === "headImage"){
var_dump($fileKey);
continue;
}
}
best and safe way to compare two string is using php strcmp function
use like this :
foreach($uploadFiles as $fileKey => $file){
if(strcmp($fileKey ,"headImage") == 0){
var_dump($fileKey);
continue;
}
}
PHP strcmp function Document

Categories