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
Related
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'].'" />';
}
}
}
I have an array which contains data from the database:
$responses = FormResponses::where('form_id', '>=', $phoneFirstElement->id)->where('form_id', '<=', $phoneLastElement->id)->get();
$responsesArray = $responses->toArray();
Then my nested loop:
foreach ($phone as $key => $value2) // Populate Phone Numbers Horizontally
{
$sheet->cell($start.'9', $value2->phone);
// This will fill the responses for each number
foreach ($metrics as $key => $value)
{
$form_id = $value2->id;
$metrics_id = $value->id;
$neededObjects = array_filter(
$responsesArray,
function ($e) use ($form_id, $metrics_id) {
return $e['form_id'] == $form_id && $e['metrics_id'] == $metrics_id;
}
);
var_dump($neededObjects);
exit;
//$responses = FormResponses::where('form_id', '=', $value2->id)->where('metrics_id', '=', $value->id)->get();
//$sheet->cell($start.$count, $neededObjects[$counter]['response']);
$sheet->cell('C'.$count, $value->question);
$sheet->cell('B'.$count, $value->description);
$sheet->cell('A'.$count, $value->metrics_name);
$counter++;
$count++;
$neededObjects = array();
}
$start++;
$count = 10;
//$counter = 0;
}
My $responsesArray is the data which has lots of record, so I want to extract those data to get the specific one I need using array_filter and storing it in
$neededObjects
However when I make a var_dump I get something like
array (size=1)
0 =>
array (size=7)
'id' => int 141730
'form_id' => int 4430
'metrics_id' => int 1
'response' => string 'Yes' (length=3)
'remarks' => string '' (length=0)
'created_at' => string '2015-11-23 19:30:07' (length=19)
'updated_at' => string '2015-11-23 19:30:07' (length=19)
Then when the next records loops in
array (size=1)
1 =>
array (size=7)
'id' => int 141731
'form_id' => int 4430
'metrics_id' => int 2
'response' => string 'Yes' (length=3)
'remarks' => string '' (length=0)
'created_at' => string '2015-11-23 19:30:07' (length=19)
'updated_at' => string '2015-11-23 19:30:07' (length=19)
I don't understand why it is increamenting. The first one is 0 then next is 1 . Yes given that I am making an array_filter inside a nested loop but I didn't put any inreament vairables to it and the array filter will aways give me 1 record of data so I am expecting it atleast to be in index 0 or just a format like this:
array (size=7)
'id' => int 141731
'form_id' => int 4430
'metrics_id' => int 2
'response' => string 'Yes' (length=3)
'remarks' => string '' (length=0)
'created_at' => string '2015-11-23 19:30:07' (length=19)
'updated_at' => string '2015-11-23 19:30:07' (length=19)
Any results that are returned by array_filter maintain their old keys. If you want the keys to reset then apply array_values to the result.
If you only want one result then call current() or array_pop() on the result to get the first record.
Even if array_filter returns one record, it will still be in the original array with the same key.
array_filter returns the array elements with their keys intact depending upon your filter function. So the keys (0, 1 etc) are the keys in your original array. Use array_pop to get the only element in your array.
I have an php array like this (var_dump)
I need change one of it's element
array (size=204)
'Address' =>
array (size=3)
'City' =>
array (size=3)
0 => string 'return $this->hasOne(City::className(), ['id' => 'cityId']);'
1 => string 'City' (length=4)
2 => boolean false
'CityDistrict' =>
array (size=3)
0 => string 'return $this->hasOne(CityDistrict::className(), ['id' => 'cityDistrictId']);' (length=76)
1 => string 'CityDistrict' (length=12)
2 => boolean false
'Contacts' =>
array (size=3)
0 => string 'return $this->hasMany(Contact::className(), ['addressId' => 'id']);'
1 => string 'Contact' (length=7)
2 => boolean true
'City' =>
array (size=3)
'Addresses' =>
array (size=3)
0 => string 'return $this->hasMany(Address::className(), ['cityId' => 'id']);'
1 => string 'Address' (length=7)
2 => boolean true
'Region' =>
array (size=3)
0 => string 'return $this->hasOne(Region::className(), ['id' => 'regionId']);' (length=64)
1 => string 'Region' (length=6)
2 => boolean false
'CityDistricts' =>
array (size=3)
0 => string 'return $this->hasMany(CityDistrict::className(), ['cityId' => 'id']);'
1 => string 'CityDistrict' (length=12)
2 => boolean true
'CityDistrict' =>
array (size=2)
Addresses =>
array (size=3)
0 => string 'return $this->hasMany(Address::className(), ['cityDistrictId' => 'id']);'
1 => string 'Address' (length=7)
2 => boolean true
'City' =>
array (size=3)
0 => string 'return $this->hasOne(City::className(), ['id' => 'cityId']);'
1 => string 'City' (length=4)
2 => boolean false
How can i change value 'CityDistrict' in this loop? or 'Addresses'? using php foreach
My code doesn't work please help understand what wrong!
private static function checkExistClass($relations)
{
foreach ($relations as $name => $relation) {
foreach ($relation as $functionName => $functionValue) {
$functionNameGet = 'get' . $functionName;
$directory = new Model;
if (method_exists($directory, $functionNameGet)) {
$relation['funky_key_' . $functionName] = $functionValue;
unset($relation[$functionName]);
}
}
}
return $relations;
}
I interprete your question that you want to rename the array index Addresses to NewAddresses:
$relations['CityDistrict']['NewAddresses'] = $relations['CityDistrict']['Addresses'];
unset($relations['CityDistrict']['Addresses']);
EDIT:
to do that in your foreach loop, change:
$relation['funky_key_' . $functionName] = $functionValue;
unset($relation[$functionName]);
to:
$relations[$name]['funky_key_'.$functionName] = $functionValue;
unset($relations[$name][$functionName]);
maybe this is what you're looking
if (isset($array['n'])) {
$array['name'] = $array['n'];
unset($array['n']);
}
you can see the complete post in Change key in associative array in PHP
see you!
PD Sorry, for my english is not the best
Your loop seems wrong. In the outer loop, $name assumes values such as 'Address', and $relation is an array such as { 'City' => ..., 'CityDistrict' => ... }.
So in the second loop $functionName assumes values such as City, CityDistrict and Contacts.
If you want to change that, you need to do something like #hellcode suggested:
if ('CityDistrict' == $functionName) {
$relations[$name]['NewDistrict'] = $relations[$name][$functionName];
unset($relations[$name][$functionName]);
continue;
}
This looks like a Laravel/Eloquent problem to me. If you can state more precisely what it is that you're trying to accomplish, possibly someone could be of more use.
Also, you seem to want to create a function given its code in a string. To do this you would need create_function (or declare the function as anonymous/lambda function):
$code = "return 42;";
$array['function'] = create_function('', $code);
print $array['function']();
Note that the use of create_function is somewhat deprecated. Also you need a PHP > 5.3+ (or 5.4+ if you go lambda and require $this).
I am trying to parse out certain things within the JSON code, but the problem is that the two groups of arrays that have the information in it I need have random names, here is from the var_dump:
array (size=2)
'results' =>
array (size=1)
0 => string 'Phone.5d5b6fef-a2e0-4b08-cfe3-bc7128b776c3.Durable' (length=50)
'dictionary' =>
array (size=3)
'Person.51f28c76-2993-42d3-8d65-4ea0a66c5e16.Ephemeral' =>
array (size=8)
'id' =>
array (size=5)
...
'type' => null
'names' =>
array (size=1)
...
'age_range' => null
'locations' => null
'phones' =>
array (size=1)
...
'best_name' => string 'John Smith' (length=15)
'best_location' => null
'Location.28dc9041-a0ee-4613-a3b0-65839aa461da.Durable' =>
array (size=30)
'id' =>
array (size=5)
...
'type' => string 'ZipPlus4' (length=8)
'valid_for' => null
'legal_entities_at' => null
'city' => string 'City' (length=8)
'postal_code' => string '12345' (length=5)
'zip4' => string '4812' (length=4)
'state_code' => string 'MO' (length=2)
'country_code' => string 'US' (length=2)
'address' => string 'Main St, City, MO 12345-4812' (length=33)
'house' => null
No I am trying to get best_name from under the part that starts with Person and address under Location. But when I do:
$string = file_get_contents($url);
$json=json_decode($string,true);
var_dump($json);
echo $json['dictionary']['Person']['best_name'];
I get Undefined index: Person error, because the actual object name for Person is:
Person.51f28c76-2993-42d3-8d65-4ea0a66c5e16.Ephemeral which is different every time I do a search. Is there a way to do this without putting the random generated line in?
Hopefully this makes sense, thanks for the help in advance!
If the Person key always starts with the string "Person", than simply do a foreach and check the key which contains this string.
Like:
foreach ($json['dictionary'] as $key => $value) {
if (preg_match('/^Person/', $key)) {
echo $json['dictionary'][$key]['best_name'];
}
}
Of course this get complicated, if you have multiple keys which start with "Person".
You can do the same with "Location" or any other string you need.
How about something like this ... loop through $json['dictionary']'s index keys to find something that starts with "Person".
$foundIt = false;
foreach (array_keys($json['dictionary']) as $key) {
if (substr($key,0,6) == 'Person') {
$foundIt = $key;
break;
}
}
if ($foundIt) { echo $json['dictionary'][$foundIt]['best_name']; }
In database, Student_id is containing 0 value. I want to check it in if condition, but required result is not achieved. I have tried following scenarios in if condition:
if(is_null($item['student_id'])) {}
if($item['student_id'] === 0){}
if($item['student_id'] == 0){}
if(intval($item['student_id']) == 0){}
if(strval("$item['student_id']") == "0"){}
Note: Currently Iam trying to print some message in if conditions. But on student_id = 0, nothing is printed. If student_id is other than 0, then print is working fine.
Can some one guide me what Iam doing wrong and how it can be rectified.
I have added var_dump
array
'_id' =>
object(MongoId)[2]
public '$id' => string '50906d7fa3c412bb040eb577' (length=24)
'student_id' => int 0
'type' => string 'exam' (length=4)
'score' => float 54.653543636265
array
'_id' =>
object(MongoId)[6]
public '$id' => string '50906d7fa3c412bb040eb578' (length=24)
'student_id' => int 0
'type' => string 'quiz' (length=4)
'score' => float 31.950044967421
array
'_id' =>
object(MongoId)[2]
public '$id' => string '50906d7fa3c412bb040eb579' (length=24)
'student_id' => int 0
'type' => string 'homework' (length=8)
'score' => float 14.850457681164
This should work unless your value is not really 0.
if(intval($item['student_id']) == 0){}
Else another way that could work is this, you almost had it:
if($item['student_id'] === '0'){}
But then again, make sure you REALLY have a 0 in there... can you var_dump $item for us just to make sure?
try:
if((int) $item['student_id'] === 0){
....
}
if((int)$item['student_id'] === 0){}
to compare zero by value , first change the retrieved data to integer, then compare using === sign to make sure they are equivalent in both value and type:
if(intval($item['student_id']) === 0){}