how get array data with foreach loop in this code? - php

This is my array:
$customer_info=[
array(
'name'=>array(
'fistname'=>'jason',
'lastname'=>'jason'
),
'id'=>'1'
),
array(
'name'=>'name2',
'id'=>'1'
)
];
and I want to get firstname and lastname from this array .

array_column($customer_info, 'name') should give you an array of all 'name' elements in your 2d array. I'll edit the answer if you can explain better what you want to do here.
If you really want to do it with a foreach loop, simply:
$output = [];
foreach ($customer_info as $row) {
$output[] = $row['name']
}

Should be fairly straight-forward, but we are looping through your array, checking if 'name' is an array or a string, and handling both scenarios.
This will display the information on the page, I wasn't sure if this is what you wanted or if you wanted to store the information into an array for use later.
If you want this stored as an array, what is the format of the array you need, are you going to concatenate the first and last names or store them in a multi-dimensional array?
foreach($customer_info as $key => $customer) {
if(is_array($customer['name'])) {
echo 'First Name: ' . $customer['name']['firstname'] . '.<br />';
echo 'Last Name: ' . $customer['name']['lastname'] . '.<br />';
} else {
echo 'Name is: ' . $customer['name'] . '.<br />';
}
}

this should work fine:
for first array:
$name = $customer_info[0]['name']['fistname'];
$family = $customer_info[0]['name']['fistname'];
for second array:
$name = $customer_info[1]['name'];

Related

How can I fix my code to make it function?

I'm new in PHP (and in programming altogether). I have watched a video explaining the basics, so I decided to play around with PHP by myself; I wrote this code:
<?php
$people = [
array("John", "smart"),
array("Mike", "dumb"),
array("Jose", "smart"),
array("Emmanuel", "dumb")
];
foreach ($people as $name => $intelligence) {
};
echo $name [0][0]." "."is ". $intelligence[0][1];
?>
I'm trying to output:
John is smart
However, it outputs:
is m
I'm not sure how to fix this.
Please help, thank you.
Your array data (per item) looks like this:
[
'john',
'smart'
]
There is no key association to these values. So in your output example, what you actually need to do is:
foreach ($people as $el)
{
echo $el[0]. ' is ' .$el[1];
}
Your data is a numerically indexed array, starting at 0. So 0 = john and 1 = smart.
It would be better to structure your array like this:
$people = [
0 => [
'name' => 'john',
'intelligence' => 'smart'
], # etc.
];
foreach ($people as $el)
{
echo $el['name']. ' is ' .$el['intelligence'];
}
here we're using named keys that make sense.
In your code example you do this:
foreach ($people as $name => $intelligence)
but $name in your loop is actually the item key.. so 0, 1 etc. and intelligence is the array. Not the name and intelligence as you think.
However, if you're literally just trying to echo out the first element, just do:
echo $people[0][0]. ' is ' .$people[0][1];
I think this is what you meant:
<?php
$people = [
array("John", "smart"),
array("Mike", "dumb"),
array("Jose", "smart"),
array("Emmanuel", "dumb")
];
foreach ($people as $person) {
echo $person[0] ." is ". $person[1]."<br/>";
}
Your people array is fine if that's really the way you want to write it.
You could instead declare it like the following. As another exercise, why don't you declaring the array like this and they modify the rest of the code so it prints what you want.
$people = [
"John" => "smart",
"Mike" => "dumb",
"Jose" => "smart",
"Emmanuel" => "dumb"
];
Your echo statement was outside of the for loop. I moved it inside.
The way you were reading your people array didn't seem quite right, so I've changed it to:
$person[0] - Get the zeroth element in the inner array, the name
$person[1] - Get the first element in the array, the intelligence
Change this
<?php
$people = [
array("John", "smart"),
array("Mike", "dumb"),
array("Jose", "smart"),
array("Emmanuel", "dumb")
];
foreach ($people as $name => $intelligence) {
};
echo $name [0][0]." "."is ". $intelligence[0][1];
?>
to this
$people = [
"John" => "smart",
"Mike" => "dumb",
"Jose" => "smart",
];
foreach ($people as $name => $intelligence) {
echo $name." is ". $intelligence;
};
You can create a simple function passing it params eg. Name to find and array of people.
<?php
$people = [
["John", "smart"],
["Mike", "dumb"],
["Jose", "smart"],
["Emmanuel", "dumb"]
];
function return_Sentence( $name , $array ){
foreach ($array as $details) {
if($name == $details[0]){
return $details[0] . ' is ' . $details[1];
}
}
return 'Not Found';
}
echo return_Sentence( "John" , $people );
?>

how to get next and prev item on array with custom key in php

I have an array with custom key value, not incremental
e.g.
$array_same_cat = array("SF124" => "value", "XA127" => "value2", "AT257" => "value3");
Now what I am working on is to search having a key value (XA127) the previous key and the next key and their value.
Here below the code that generate the array:
$array_same_cat = array();
if($loop_arrows->have_posts()){
while($loop_arrows->have_posts()){
$loop_arrows->the_post();
$current_id = get_the_ID();
$this_prod_sku = get_post_meta( $current_id, '_sku', true );
$array_same_cat[$this_prod_sku] = esc_url(get_permalink(intval($this_prod_sku)));
}
}
Added this
With this foreach I found the exact position of my element. Now I have to find how to do prev and next.
foreach($array_same_cat as $ar){
if($ar == $array_same_cat[$current_sku]){
echo 'found';
}
}
What i understand from your question:-
You have array
You have a key, which you want to search in array and then you need to find-out prev and next value after it
Now you can do it like below:-
<?php
$array_same_cat = array("SF124" => "value", "XA127" => "value2", "AT257" => "value3");
$search_key = 'XA127';
$keys_array = array_keys($array_same_cat);//get keys array from original array
$get_search_value_key_from_value_array = array_search($search_key,$keys_array); // get index of given key inside keys array
$prev_key = $keys_array[$get_search_value_key_from_value_array -1]; // get previous key based on searched key index
$next_key = $keys_array[$get_search_value_key_from_value_array+1];// get next key based on searched key index
echo "Current key = ".$search_key." and current value = ".$array_same_cat[$search_key]."\n";
echo "Next key = ".$next_key." and next value = ".$array_same_cat[$next_key]."\n";
echo "Prev key = ".$prev_key." and prev value = ".$array_same_cat[$prev_key]."\n";
Output:-https://eval.in/873723
PHP doesn't have a way of setting the array pointer to a specific key. For your use case, this would work:
//...some code where $array_same_cat is defined
$key = 'XA127';
$next = null;
$prev = null;
if(isset($array_same_cat[$key])){
reset($array_same_cat); //reset the array pointer to the beginning
//Iterate over the array, setting $key to the current array key
while( ($key = key(current($array_same_cat))) !== null ){
if($key == $search){
prev($array_same_cat);
$prev = array('key' => key($array_same_cat), 'value' => current($array_same_cat));
next(next($array_same_cat));
$next = array('key' => key($array_same_cat), 'value' => current($array_same_cat));
break;
}
next($array_same_cat);
}
}
if( !empty($prev) ){
echo "Previous element: key=" . $prev['key'] . ', value= ' . $prev['value'] . PHP_EOL;
}
if( isset($array_same_cat[$search] ){
echo "current element: key=" . $search . ', value= ' . $array_same_cat[$search] . PHP_EOL;
}
if( !empty($next) ){
echo "Next element: key=" . $next['key'] . ', value= ' . $next['value'] . PHP_EOL;
}
This code will output something like:
Previous element: key=SF124, value=value
Current element: key=XA127, value=value2
Next element: key=AT257, value=value3
Note, there is likely a better way to structure your data so that you can avoid having to do something like this. The above method is not very efficient since it requires that you loop over the entire array until you find the key you're looking for.
A better approach might involve storing the next and previous values along with the current value as you loop through your posts.

Wordpress and custom fields in a loop

Say I have custom fields with the keys p_title_1 p_value_1 p_title_2 p_value_2
Each of these has values within them and I would like to loop through p_title_[i] and p_value_[i] and show them on the page so that title and value would be grouped together in their own div.
I can't seem to figure out how to write it as a loop to show the 1's together and 2's together.
Reason it needs to be in a loop is incase more custom fields get added in the future. At current I have the following but it only echos the key and value
<?php
$custom_fields = get_post_custom( get_the_ID() );
$my_custom_field = $custom_fields['p_title_1'];
foreach ( $my_custom_field as $key => $value )
echo $key . " => " . $value . "<br />";
?>
Help is appreciated
Use the field name to build an array.
Where the array looks like:
array
1 =>
array
'title' => 'title 1'
'value' => 'value 1'
Loop through your fields and add to the array:
You can get the array index using explode function
$parts = explode ( '_' , $fieldname );
$name = $parts[0];
$index = $parts[1];
And add the value to the array:
$array[$index][$name] = $value;

Using foreach loop through array in an array using php

I am fairly new to PHP and have been working on looping through this array for days...sigh...
http://pastebin.com/Rs6P4e4y
I am trying to get the name and headshot values of the writers and directors array.
I've been trying to figure out the foreach function to use with it, but have had no luck.
<?php foreach ($directors as $key => $value){
//print_r($value);
}
?>
Any help is appreciated.
You looking for some such beast? You didn't write how you wanted to process them, but hopefully this helps you.
$directors = array();
foreach( $object->people->directors as $o )
$directors[] = array( 'name' => $o->name, 'headshot' => $o->images->headshot );
$writers = array();
foreach( $object->people->writers as $o )
$writers[] = array( 'name' => $o->name, 'headshot' => $o->images->headshot );
var_dump( $directors );
var_dump( $writers );
Last note, if there's no guarantee that these members are set, you use isset before any dirty work.
Hope this helps.
Use -> to access properties of the objects.
foreach ($directors as $director) {
echo 'Name: ' . $director->name . "\n";
echo "Headshot: " . $director->images->headshot . "\n";
}
Your solution has already been posted, but I want to add something:
This isn't an Array, it's an object. Actually the directors property of the object is an Array. Look up what an object is and what associative arrays are!
Objects have properties, arrays have keys and values.
$object = new stdClass();
$object->something = 'this is an object property';
$array = new array();
$array['something'] = 'this is an array key named something';
$object->arrayproperty = $array;
echo $object->arrayproperty['something']; //this is an array key named something
Good luck with learning PHP! :)
Having variable $foo, which is an object, you can access property bar using syntax:
$foo->bar
So if you have an array od directors named $directors, you can simply use it the same way in foreach:
foreach ($directors as $value){
echo $value->name." ".$value->images->headshot;
}

Creating a link with implode only makes one array item a link?

$fidimp = implode('"', $fidarr);
$friendsimp = implode('<a href="../profile?id=', $funamearr);
$impglue = '</a><br />' . $fidimp . '>';
echo('<a href="../profile?id=' . $fidimp . '>' . implode('</a><br />', $funamearr));
This is the code I'm working with.
$funamearr has 2 values in it: "Conner" and "Rach667"
$fidarr has 2 values in it as well: "2" and "3" (the user's id's)
When this code is run, it only makes "Conner" a link (it works, by the way) How can I make it so that "Rach667" shows up as a link too?
First build an associative array from your ids to your names, then create an array of links and implode it, something like:
<?php
$funamearr = array( "Conner", "Rach667" );
$fidarr = array( 2, 3 );
$users = array_combine($fidarr, $funamearr);
foreach($users as $id => $name) {
$links[] = sprintf('%s', $id, $name);
}
echo implode('<br/>', $links);
Well I don't recommend using implode in this case but as said by LokiSinclair to use a loop.
<?php
foreach($funamearr as $key => $value) {
echo '' . $value . '<br/>";
}
This case assumes that the array keys of $funamearr and $fidarr match with eachother.
Outside the code I would make two tips.
1 Use usefull variable names.
$funamearr is not telling me much, except the arr part because it probably is an array. I would recommand $usernames (multiple so array ;)
2 Keep data together
No we have to hope that the keys are the same. but if you keep the data at the same level we won't and ofter easier in use
ie
array(
array(
'id' => 1,
'name' => 'test',
),
array(
'id' => 2,
'name' => 'test_name_2',
),
)

Categories