douxie2029 2016-08-06 05:27
浏览 28
已采纳

PHP:如何在将数组项传递给函数时输出键本身?

Given array item $array["first level"]["second LVL"], how can I get the key string second LVL itself, not the key-value-pair value?

More Detailed Example

I have an array item variable $array["address"]["city"] that I am passing to a function like so:

<?php

printKey( $array["address"]["city"] );

function printKey( $array_item ) {
    return "Output: " . keyValue(array_item);
}

?>

How can I get the key value string city itself from the array item $array["address"]["city"]?

I've seen array_search(), array_keys(), and key(), but none seem to do the trick without a for loop at the least.

EDIT / Clarification:

The problem is, for example, sometimes my function is passed $array["address"]["name"] and sometimes it passes $array["address"]["company"].

I need to be able to dynamically output Name: or Name:

Example function:

$array["address"]["name"] = "Andre";
$array["address"]["company"] = "StackNot";

function printITEMkeyAndValue( $arrayITEM ) {
    //It's not possible to do a for loop on just an item, right? It's just a string (?)
    return $array_item_key . ": " . $array_item_value;
}

echo printITEMkeyAndValue( $array["address"]["name"] );
echo printITEMkeyAndValue( $array["address"]["company"] );

Desired output:

Name: Andre
Company: StackNot
  • 写回答

3条回答 默认 最新

  • duanletao9487 2016-08-06 05:40
    关注

    I understand what you want, but see when you call printKey function with a 2 value, it is not possible to find a key, because array does not exist in the function, the solution is to send the array and your item into the function and find it by search and then get the key.

    <?php
    
    $array["address"]["city"] = 2;
    
    function printKey( $array, $item ) {
        foreach($array["address"] as $key =>$value){
            if ($value == $item){
                return "Output: " . $key;           
            }
        }
    }
    
    echo printKey($array, $array["address"]["city"]);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上